用户has_many:用户、:通过=>:朋友-怎么了?
-
18-09-2019 - |
题
这是我的代码:
class Friend < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"
end
class User < ActiveRecord::Base
#...
has_many :friends
has_many :users, :through => :friends
#...
end
当我现在开始加入的用户。
user.users << user2
user.save
只有user_id的朋友被填满,friend_id是空。
任何帮助吗?
你的, Joern.
解决方案
你需要添加的 :source
属于你的 has_many through
协会。
class User < ActiveRecord::Base
has_many :friends
has_many :users, :source => :friend, :through => :friends
end
现在的下列电话会的工作。
u1.users << u2
u.friends.last
# will print #<Friend id: 1, user_id: 1, friend_id: 4>
注:
- 轨道自动保存的协会。你需要电话
save
只有当用户模型是新的。 - 你也许应该重新命名所关联的东西更加明确。例如:
friend_users
等等。
其他提示
尝试: Railscasts - 自引用关联。一般对列出的所有话题,是非常好的教程。
我想你需要删除belongs_to的:用户在你的朋友的模型
不隶属于 StackOverflow