用户 has_many :users, :through => :朋友-怎么样?

发布于 2024-08-24 12:31:54 字数 453 浏览 10 评论 0原文

这是我的代码:

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 为空。

有什么帮助吗?

你的, 乔恩.

This is my code:

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

When I now start adding users by...

user.users << user2
user.save

Only the user_id of friend is filled, friend_id is null.

Any help?

Yours,
Joern.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

长途伴 2024-08-31 12:31:54

尝试:Railscasts - 自引用关联。一般来说,对于列出的所有主题都有非常好的教程。

Try: Railscasts - Self-Referential Associations. Generally has very good tutorials on all topics listed.

方圜几里 2024-08-31 12:31:54

您需要将 :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. Rails 自动保存关联。仅当用户模型是新的时才需要调用save
  2. 您可能应该将关联重命名为更明确的名称。例如:friend_users 等。

You need to add the :source attribute to your has_many through association.

class User < ActiveRecord::Base
 has_many :friends
 has_many :users, :source => :friend, :through => :friends
end

Now the following calls will work.

u1.users << u2    
u.friends.last
# will print #<Friend id: 1, user_id: 1, friend_id: 4>

Notes:

  1. Rails auto saves the associations.You need to call save only if the user model is new.
  2. You probably should rename the association to something more explicit. E.g: friend_users etc.
伤感在游骋 2024-08-31 12:31:54

我认为你需要删除你的朋友模型中的belongs_to:user

I think you need delete the belongs_to :user in your Friend model

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文