Rails ActiveRecord 双重关联

发布于 2024-11-27 15:43:37 字数 654 浏览 6 评论 0原文

我有以下两个模型,用户..

class User < ActiveRecord::Base
  has_and_belongs_to_many :sites
end

..和站点:

class Site< ActiveRecord::Base
  has_and_belongs_to_many :users
end

到目前为止还不错。它有效而且非常简单。 现在我想向“主要用户”介绍该网站。我将“primary_user_id”添加到网站,并尝试添加第二个关联:

class Site< ActiveRecord::Base
 has_and_belongs_to_many :user

 # my new association that doesn't work...
 has_one :primary_user, :class_name => "User", :conditions => ['id = ?', '{self.primary_user_id}'] 
end

它不喜欢它...现在我知道我可以通过向网站添加方法“primary_user”来伪造此内容,这将起作用,但我的问题是是否可以使用 ActiveRecord 关联以及如何使用?

I have the following two models, User..

class User < ActiveRecord::Base
  has_and_belongs_to_many :sites
end

.. and Site:

class Site< ActiveRecord::Base
  has_and_belongs_to_many :users
end

Up to this point its fine. It works and it's pretty simple.
Now I want to introduce "primary user" to the Site. I add "primary_user_id" to the Site, and trying to add a second association:

class Site< ActiveRecord::Base
 has_and_belongs_to_many :user

 # my new association that doesn't work...
 has_one :primary_user, :class_name => "User", :conditions => ['id = ?', '{self.primary_user_id}'] 
end

It doesn't like it... Now I know that I can fake this by just adding a method "primary_user" to the site and this will work, but my question is whether it is possible to user ActiveRecord associations and how?

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

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

发布评论

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

评论(1

毁梦 2024-12-04 15:43:37

has_and_belongs_to_many 很棘手,大多数人已经放弃它并通过 => 使用 has_many 。模型。
顺便说一句 - '到目前为止还好。它有效而且非常简单。一切都是这样开始的。当你“真正”开始使用它们时,它们的表现才是最重要的,因此你可能会发现 has_many 更容易使用。

这些链接将有所帮助:

http://paulbarry.com/articles/2007/ 10/24/has_many-through-checkboxes

http://thoughtsincomputation.com/posts/checkboxes-with-has_many-through

http:// /my.opera.com/durrantm/blog/2011/07/24/rails-simple-form-with-has-many-through-hmt-relationship

https://github.com/romanvbabenko/nested_has_many_through(嵌套 gem)。

has_and_belongs_to_many is tricky and most people have moved away from it and use has_many through => model.
btw - 'Up to this point its fine. It works and it's pretty simple.' is how all things start off. How they perform when you 'really' start to use them is what counts and for that reason you'll probably find has_many through easier to work with.

These links will help:

http://paulbarry.com/articles/2007/10/24/has_many-through-checkboxes

http://thoughtsincomputation.com/posts/checkboxes-with-has_many-through

http://my.opera.com/durrantm/blog/2011/07/24/rails-simple-form-with-has-many-through-hmt-relationship

https://github.com/romanvbabenko/nested_has_many_through (nesting gem).

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