开发者

Adding an object in a has_and_belongs_to_many association with Rails

I have this simple has_and_belongs_to_many association between users, which works perfectly.

However, I would like to add a friendship relation between all new users created and the first user (开发者_StackOverflow中文版yup, just like MySpace's Tom), directly in the Create method:

def create
  @user = User.new(params[:user])
  if @user.save
    @user.friends << User.find(1)
    redirect_to root_path
  else
    render :action => :new
  end
end

I don't understand why this doesn't work. No error, nothing, it just doesn't add the first User to the new user's friends.

(for information, I'm using Rails 2.3.4)

What should I do?

Kevin


First, you could fire up script/console and check whether your associations are working correctly in the console. Second, you must arrange the code so that the association between user and friends are before the save command.


You must add the friend before you save the user, or less efficiently save the user again after you've added the friend.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜