用户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 # 

笔记:

  1. Rails会自动保存关联。只有在用户模型是新的时才需要调用save
  2. 您可能应该将关联重命名为更明确的内容。 例如: friend_users

尝试: Railscasts – 自引用关联 。 通常对列出的所有主题都有非常好的教程。

我想你需要在你的朋友模型中删除belongs_to:user