【问题标题】:ActiveRecord Has Many ThroughActiveRecord 有很多通过
【发布时间】:2013-11-23 04:03:04
【问题描述】:

我一直在努力解决 has_many :through 关系。假设我有以下表格:

Orgs
==============
id     Integer
name   String

Accounts
==============
id     Integer
name   String
type   Integer
org_id Integer

Users
====================   
id           Integer
account_id   Integer
name         String

然后我将模型设置如下:

class Orgs < ActiveRecord::Base
  has_many :accounts
  has_many :users, through :accounts

class Accounts < ActiveRecord::Base
  has_many :users
  belongs_to :orgs 

class Users < ActiveRecord::Base
  belongs_to :accounts

如何获取帐户 type=3 的 Orgs 用户(例如)?我在哪里放置条件?

【问题讨论】:

    标签: ruby-on-rails activerecord has-many


    【解决方案1】:

    我不确定你是否想遵循这条路线,但我认为你所展示的模型之间的更好关系如下:

    class Orgs < ActiveRecord::Base
      has_many :accounts
      has_many :users, through: :accounts
    
    class Accounts < ActiveRecord::Base
      belongs_to :user
      belongs_to :org 
    
    class Users < ActiveRecord::Base
      has_many :accounts
      has_many :orgs, through: :accounts
    

    您在上面看到的是典型的has_many ... through 关系。现在有了上述关系,您将能够执行以下操作:

    org = Org.find(1)
    org.users.where('accounts.account_type = :account_type', account_type: 3)
    

    【讨论】:

      【解决方案2】:

      您可以为这种情况使用额外的范围:

      class Orgs < ActiveRecord::Base
         has_many :accounts
         has_many :users, through :accounts
         has_many :specific_users, -> { where(accounts: {type: "3"}) }, through: :accounts
      

      您可以在http://guides.rubyonrails.org/association_basics.html(4.3.3 has_many 的作用域)上查看更多信息

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-10
        • 2012-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-22
        • 1970-01-01
        • 2021-11-16
        相关资源
        最近更新 更多