Question

Using Rails 3.1.0

def create
@practice = Practice.new(params[:practice])

respond_to do |format|
  if (current_user.practices << @practice rescue false)

    pmf = current_user.practices_users.inspect # if this line is removed the following update_attributes method breaks!

    current_user.practices_users.last.update_attributes(:admin_flg => true, :first_name => params[:first_name], :last_name => params[:last_name])
    format.html { redirect_to home_dashboard_path, notice: 'Practice was successfully created.' }
    format.json { render json: @practice, status: :created, location: @practice }
  else
    format.html { render action: "new" }
    format.json { render json: @practice.errors, status: :unprocessable_entity }
  end
end
end

When the 'pmf = ...' line is not present, I get this line

NoMethodError:
   undefined method `update_attributes' for nil:NilClass

When the 'pmf = ...' line is present, the create action works normally. What is going on?

Was it helpful?

Solution

I don't know the exact answer but I can help you debug...

When you do

pmf = current_user.practices_users.inspect

then Rails is loading the whole set of practices_users (for current_user) from the database and when you call last a little bit later, it is calling the method last on an object of type Array.

When you do

current_user.practices_users.last

without having made your pmf call, the whole set of practices_users has not been loaded from the database into an array, and Rails is not going to load the whole set because all you want is the last one. It would be a waste to load an array of items when all it needs to load is the last one. So it will generate SQL that only loads a single row from the database.

In this sort of situation, you need to look at your console or development log to see exactly what SQL Rails is generating and why that SQL isn't returning any value. Then it will become clear what's going on.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top