views:

25

answers:

2

Hi,

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 (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

+2  A: 

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.

poseid
+2  A: 

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

Ronny Vindenes