用户 has_many :users, :through => :朋友-怎么样?
这是我的代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试:Railscasts - 自引用关联。一般来说,对于列出的所有主题都有非常好的教程。
Try: Railscasts - Self-Referential Associations. Generally has very good tutorials on all topics listed.
您需要将
:source
属性添加到has_many through
关联中。现在以下调用将起作用。
注意:
save
。friend_users
等。You need to add the
:source
attribute to yourhas_many through
association.Now the following calls will work.
Notes:
save
only if the user model is new.friend_users
etc.我认为你需要删除你的朋友模型中的belongs_to:user
I think you need delete the belongs_to :user in your Friend model