2

这是我的代码:

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

只有friend的user_id填写,friend_id为null。

有什么帮助吗?

你的,乔恩。

4

3 回答 3

2

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

于 2010-03-08T21:59:15.570 回答
1

您需要将该: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>

笔记:

  1. saveRails 自动保存关联。仅当用户模型是新的时才需要调用。
  2. 您可能应该将关联重命名为更明确的名称。如:friend_users等。
于 2010-03-08T20:52:37.353 回答
1

我认为您需要删除 Friend 模型中的 belongs_to :user

于 2010-03-08T20:59:36.057 回答