【问题标题】:Rails ActiveRecord Double AssociationsRails ActiveRecord 双重关联
【发布时间】:2011-08-01 09:21:13
【问题描述】:

我有以下两个模型,User..

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 关联以及如何?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord associations has-and-belongs-to-many


    【解决方案1】:

    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(嵌套宝石)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多