Hi Guys,
I have stuck while building the association for model user,
user has_many friends, friend - nothing but a user
For that i have created a model called 'Friendship', user to join user and friends. And build the association with the following relations
friendship table has the following fields
user_id
friend_id
class User < ActiveRecord::Base
has_many :friendships
has_many :friendships_by_me, :foreign_key => 'user_id', :class_name => 'Friendship'
has_many :friends_by_me, :through => :friendships_by_me, :source => :friendshipped_by_me
has_many :friendships_for_me, :foreign_key => 'friend_id', :class_name => 'Friendship'
has_many :friends_for_me, :through => :friendships_for_me, :source => :friendshipped_for_me
end
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friendshipped_for_me, :class_name => "User", :foreign_key => 'user_id'
belongs_to :friendshipped_by_me, :class_name => "User", :foreign_key => 'friend_id'
end
Thats it!!!
Now run the following commands
user = User.first
user.friends_by_me => [users] returns the collection of friends added by user.
user.friends_for_me => [users] returns the collection of friends who add user as their friend.
Note: i have referred the plugin 'has_many_friends'.
Thanks,
vaddi
No comments:
Post a Comment