Rails Recipes 18 - Self-referential relationships?

Hi everyone,

I’m building a little recipe-sharing site and I want users to add others
as “friends”, just like outlined in the Rails Recipes book, chapter 18.
I created the user model just like in the book:

has_and_belongs_to_many :friends,
:class_name => “User”,
:join_table => “friendships”,
:association_foreign_key => “friend_id”,
:foreign_key => “user_id”

The only difference is that my join table is called “Friendships”, and
my Person table is “Users”.

My problem is that I can’t figure out how to insert friendships into the
friendship table. In the book he does it in the console, and I don’t
know how to do it in my app.

In every user profile I have:

<%= link_to ‘Add as a friend’, :controller => ‘users’, :action =>
‘friendify’ %>

I just don’t know how to make my friendify action add the user_id and my
current_user as friends in the friendship table. Any ideas?

Thanks so much!

On 12/3/06, Dave A. [email protected] wrote:

:association_foreign_key => "friend_id",

<%= link_to ‘Add as a friend’, :controller => ‘users’, :action =>
‘friendify’ %>

I just don’t know how to make my friendify action add the user_id and my
current_user as friends in the friendship table. Any ideas?

For starters, you need to pass both user ids to your controller,
something like:

<%= link_to ‘Add as a friend’, :controller => ‘users’, :action
=>‘friendify’, :id=>@current_user, :friend_id=>some_other_user.id %>

You should then be able to add the friend to the collection directly:

def friendify
@user = User.find(params[:id])
@new_friend = User.find(params[:friend_id])
@user.friends << @new_friend
end

Cheers,
Max