Reputation: 407
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
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
Reputation: 42789
Join and put the query as a hash
Bill.joins(:legislator).where(legislators: {party: 'D'})
Upvotes: 1