Has_many association. Is this possible?


#1

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.


#2

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.