views:

34

answers:

1

My validations were working for a while, or so I thought. Now I come back to them after a while doing something else and I am getting the error above. I think it means I am creating a nil object with the .new method but I am just lost. It seemed to be a problem with the creation of a new object by the controller because even if I # out the validation the next validation in the tree on another attribute of @thing throws up the same error. However even if I create the object in the console and test it's there the .save method throws up the error still - undefined method 'user_id' for nil:NilClass

ThingsController:

def create
  @thing = Thing.new(params[:thing])
  @thing.user_id = @currentuser_id

  if @thing.save
    flash[:notice] = "Successfully created thing."
    redirect_to @thing
  else
    #flash[:notice] = "Your thing did not get created."
    render 'otherthings/show'      
  end
end

Thing.rb
  validate :user_valid
  def user_valid
    errors.add("you must be logged in to add a thing") unless @thing.user_id?
  end

I'm a bit of a ruby on rails noob (i.e. <8weeks) and this is my first stackoverflow question, so go easy on me if this is stupidly obvious. I've tried params["thing"] too, as that worked in the console after manually creating params to match the log files (whereas params [:thing] didn't) but that doesn't change anything in terms of the error message I get.

+2  A: 

When you are calling unless @thing.user_id?, it's flipping out because there's no @thing (it doesn't get passed from your controller to your model as an instance variable).

I don't remember how exactly it works, but I'm pretty sure that when calling validate :user_valid, it will pass along the record to be validated for you. If that's indeed the case you could try:

def user_valid
  errors.add("you must be logged in to add a thing") unless user_id?
end
theIV
If he is already in the `Thing` model he should be able to use `user_id?` or `user.present?` (if it's an association)
Garrett
Thanks, I realized that afterwards. I'll fully update the answer to reflect that.
theIV
Thanks - you guys are really helpful... this certainly seemed to fix the problem with user_id and I think I probably have some similar issues with other validations I should be able to figure out through some trial and error after digesting your brief simple explanation.
Richard Jordan