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.

1
  • the error was popped up referring to the controller call on thing.save and then on the model line starting errors.add ...but i think the guys below answered for me :-) Commented Oct 4, 2010 at 22:55

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

If he is already in the Thing model he should be able to use user_id? or user.present? (if it's an association)
Thanks, I realized that afterwards. I'll fully update the answer to reflect that.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.