ActiveRecord Has_many通过

时间:2013-11-23 04:03:04

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

我一直在与has_many挣扎:通过关系。我们说我有以下表格:

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

我如何获得Orgs&#39;账户类型= 3的用户(例如)?我在哪里放置条件?

2 个答案:

答案 0 :(得分:3)

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

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)

答案 1 :(得分:0)

您可以在这种情况下使用其他范围:

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的范围)中查看更多相关信息