Forum: Ruby on Rails has_many association. Is this possible??

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
48cc9239dcaa0b7870a52e89c8016734?d=identicon&s=25 TheZ (Guest)
on 2008-10-03 04:21
(Received via mailing list)
I have the following schema.

table: user
  t.column :id, :integer

table: friends
  t.column :user_id,   :integer  #Owner of this friendship
  t.column :friend_id, :integer  #FK to User table

table: activity
  t.column :user_id

Basically I want to display all activity from friends that i have

I currently have the following has_many finder...

has_many :friend_activities,
    :class_name => 'Activity',
    :finder_sql => 'select a.* from activities a, friend f where
a.user_id = f.friend_id and f.user_id = #{id}'

Is it even possible to change the above has_many to not user
the :finder_sql but using some combination
of :through, :source ... ???? If so can someone please help.
280b78a61a968391b7e07e912be102a8?d=identicon&s=25 Robert Walker (robert4723)
on 2008-10-03 15:13
I'll be making a few assumptions here since your full schema is not
shown here, but this is what I can deduce from your description:

1. You have a reflexive many-to-many relation from User back to User
though Friend.
2. Friend has it's own model class so has it's own identity (and id
column).

table: friends
   t.column :id, :integer # <-- I added this here for clarification
   t.column :user_id,   :integer  #Owner of this friendship
   t.column :friend_id, :integer  #FK to User table

Given both 1 & 2 above are true, you could add another many-to-many
relation for Friend and Activity through FriendActivity:

table: friend_activities
   t.column :friend_id, :integer  #FK to friends table
   t.column :activity_id,   :integer  #FK to activities table

I didn't put a ton of thought into this, but I believe it's the approach
I would try first.

TheZ wrote:
> I have the following schema.
>
> table: user
>   t.column :id, :integer
>
> table: friends
>   t.column :user_id,   :integer  #Owner of this friendship
>   t.column :friend_id, :integer  #FK to User table
>
> table: activity
>   t.column :user_id
>
> Basically I want to display all activity from friends that i have
>
> I currently have the following has_many finder...
>
> has_many :friend_activities,
>     :class_name => 'Activity',
>     :finder_sql => 'select a.* from activities a, friend f where
> a.user_id = f.friend_id and f.user_id = #{id}'
>
> Is it even possible to change the above has_many to not user
> the :finder_sql but using some combination
> of :through, :source ... ???? If so can someone please help.
This topic is locked and can not be replied to.