用户has_many:用户,:通过=>:朋友 – 怎么样?
这是我的代码:
class Friend "User", :foreign_key => "friend_id" end class User :friends #... end
当我现在开始添加用户…
user.users << user2 user.save
只填充了friend的user_id,friend_id为null。
有帮助吗?
你的,乔恩。
您需要has_many through
关联将: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 #
笔记:
- Rails会自动保存关联。只有在用户模型是新的时才需要调用
save
。 - 您可能应该将关联重命名为更明确的内容。 例如:
friend_users
等
尝试: Railscasts – 自引用关联 。 通常对列出的所有主题都有非常好的教程。
我想你需要在你的朋友模型中删除belongs_to:user