user3809888
user3809888

Reputation: 407

Active Record query for has_many/belongs_to associations

I have built a Rails app that has data about the US Congress. I have a Legislator model and a Bill model:

class Legislator < ActiveRecord::Base
  has_many :bills
end

class Bill < ActiveRecord::Base
  belongs_to :legislator
end

So bills that a legislator has sponsored are tied to that legislator. The legislator also has a "party" attribute that is either "R", "D", or "I"

I want to get a list of all bills that were sponsored by all legislators from a particular party, e.g., all bills that were sponsored by Democrat. What would this query look like?

Upvotes: 0

Views: 800

Answers (2)

messanjah
messanjah

Reputation: 9278

Bill.joins(:legislator).where(legislators: {party: "I"})

But I would advise you to write scopes on Legislator and Bill

# class Legislator
scope :by_party, ->(party) do
  where(party: party)
end

# class Bill
scope :sponsored_by_party, ->(party) do
  joins(:legislator).merge(Legislator.by_party(party))
end

Then you can write

Bill.sponsored_by_party("I")

Upvotes: 2

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42789

Join and put the query as a hash

Bill.joins(:legislator).where(legislators: {party: 'D'})

Upvotes: 1

Related Questions