carbotex
carbotex

Reputation: 569

ActiveRecord Has Many Through

I've been struggling with has_many :through relationship. Let's say I have the following tables:

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

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

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

Then I setup the models as follow:

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

How do I get Orgs' users with account's type=3 (for example)? Where do I place the condition?

Upvotes: 1

Views: 267

Answers (2)

Ivan Antropov
Ivan Antropov

Reputation: 414

You can use additional scope for this case:

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

You can see more about this at http://guides.rubyonrails.org/association_basics.html (4.3.3 Scopes for has_many )

Upvotes: 0

vee
vee

Reputation: 38645

I'm not sure if you want to follow this route but I think a better relationship among the models you've presented would be as follows:

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

What you see above is a typical has_many ... through relationship. Now with the above relationship you will be able to do the following:

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

Upvotes: 3

Related Questions