开发者

Am i creating a nil object? (undefined method ___ for nil:NilClass) error - ruby on rails

My validations were working for a while, or so I thought. Now I come back to t开发者_如何转开发hem 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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜