I tried to use habtm relationship , but I need to use a uid as foreign key
SELECT "friends".* FROM "friends" INNER JOIN "friendships" ON "friends"."uid" = "friendships"."uid" WHERE "friendships"."user_id" = 4
#User
has_and_belongs_to_many :friends, :class_name => "Friend", :join_table => "friendships", :association_foreign_key => "uid"
#Friend
has_and_belongs_to_many :users, :class_name => "User", :join_table => "friendships", :foreign_key => "uid"
SELECT "friends".* FROM "friends" INNER JOIN "friendships" ON "friends"."id" = "friendships"."uid" WHERE "friendships"."user_id" = 4
Following the Rails Style Guide :
Prefer has_many :through to has_and_belongs_to_many. Using has_many :through allows additional attributes and validations on the join model
In your case:
class Friendship < ActiveRecord::Base
belongs_to :friend
belongs_to :user
# the validates are not mandatory but with it you make sure this model is always a link between a Friend and a User
validates :user_id, :presence => true
validates :uid, :presence => true # the Foreign Key is 'uid' instead of 'friend_id'
end
class User < ActiveRecord::Base
has_many :friends, :through => :friendships
end
class Friend < ActiveRecord::Base
has_many :users, :through => :friendships, :foreign_key => "uid"
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.