has_and_belongs_to_many refer to same Model

513 views
Skip to first unread message

Allen Walker

unread,
Aug 24, 2009, 6:24:55 PM8/24/09
to rubyonra...@googlegroups.com
I have a User model and in I want to have a

has_and_belongs_to_many :users

Obviously that won't work since the join table will have the same column
names (user_id).

What approach should I take?

thanks
--
Posted via http://www.ruby-forum.com/.

Rick DeNatale

unread,
Aug 24, 2009, 8:42:36 PM8/24/09
to rubyonra...@googlegroups.com
On Mon, Aug 24, 2009 at 6:24 PM, Allen
Walker<rails-mai...@andreas-s.net> wrote:
>
> I have a User model and in I want to have a
>
> has_and_belongs_to_many :users
>
> Obviously that won't work since the join table will have the same column
> names (user_id).
>
> What approach should I take?

You need to give the association a different name, and a few other things

class User
has_and_belongs_to_many :friends,
:class => "User",
:association_foreign_key =>
"friend_id",
:join_table => "friends_users"
end


You then need to make a join table named "friends_users" with no
primary key and user_id and friend_id columns.

--
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

Allen Walker

unread,
Aug 25, 2009, 4:26:19 PM8/25/09
to rubyonra...@googlegroups.com
Thanks. one thing I noticed is that it's ":class_name" not just ":class"
(2.3.3)

Rick Denatale wrote:

>
> You need to give the association a different name, and a few other
> things
>
> class User
> has_and_belongs_to_many :friends,
> :class => "User",
> :association_foreign_key =>
> "friend_id",
> :join_table =>
> "friends_users"
> end
>
>
> You then need to make a join table named "friends_users" with no
> primary key and user_id and friend_id columns.
>
--

Posted via http://www.ruby-forum.com/.

Reply all
Reply to author
Forward
0 new messages