Ruby on rails habtm外键

Ruby on rails habtm外键,ruby-on-rails,Ruby On Rails,我尝试使用habtm关系,但我需要使用uid作为外键 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 => "fr

我尝试使用habtm关系,但我需要使用uid作为外键

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
以下是:

喜欢有很多:通过有很多和属于很多。使用has_many:through允许在连接模型上添加属性和验证

就你而言:

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
类友谊true
验证:uid,:presence=>true#外键是“uid”而不是“friend\u id”
结束
类用户:友谊
结束
类友元:友谊,:外键=>“uid”
结束