开发者

Rails, saving the foreign key in a `belongs_to` association

I think I'm having a really basic problem here but I can't seem to put my finger on what I'm doing wrong.

So the issue here is when I save an instance of a model the foreign_key for the models's belongs_to association (in this case the user_id is not being saved, so I'm forced to do this:

def new
  @thing = Thing.new(:user_id => current_user.id)
end

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

  if @thing.save
    redirect_to @thing
  else
    render 'new'
  end
end

Shouldn't the user_id get saved automatically if my model has this association?

class Thing < ActiveRecord::Base
  belongs_to :user
end

The reason I'm having this issue in the first place is because the gem frien开发者_StackOverflow中文版dly_id has changed the way all of my ids work and now return the objects slug... pretty annoying in my opinion.


I would try @thing.user = User.find(current_user.id) instead in your controller. Have you also got the has_many :things association declared in your user model?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜