randika
randika

Reputation: 1539

Rails 3 Scope with :has_many :through association

In my latest rails app I have these 3 models - Entries, Politician and Parties. Simply the app is for adding "Entries" for "Politicians". Lets assume an entry has (entry name, date). Parties of politicians are recorded withing the Memberships model and also I record the time-frames of each memberships. So the records in memberships looks like below.

politician_id, party_id, date_from, date_to 

The models

class Politician < ActiveRecord::Base
  has_many :memberships
  has_many :parties, :through => :memberships do
  has_many :entries
end

class Party < ActiveRecord::Base
  has_many :memberships
  has_many :politicians, :through => :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :politician
  belongs_to :party
end

Now let's say we have Entry record of Politician id 148, "148","My entry name", "2010-01-25"in the table and I need to find the Party membership of this politician for this entry based on the dates on both the tables. Assuming in the memberships table we have these records. I think its a scope I must use here?

politician_id | party_id | date_from | date_to 

148 | 10 | 2012-01-22 | 2013-01-22
148 | 16 | 2010-01-21 | 2012-01-21
148 | 45 | 2009-01-19 | 2010-01-20

Upvotes: 1

Views: 1346

Answers (1)

TheIrishGuy
TheIrishGuy

Reputation: 2583

I recommend this way, using chained scopes, it will work for you and more flexible down the road

Add a scope to politician to find by name;

scope :by_name, lambda{|name| name: name }

Then add a scope to your membership model to find list all memberships to fit your range

scope :by_date, lamda{|x,y| where("date_from > ? and date_to < ?, x,y) }

This will allow you to say something like

Party.memeberships.by_date(YOURFROMDATE, YOURTODATE).by_name(YOURPOLITICIAN)

These are a couple ways to do this but i like the sere pare t scope for reuse illy down the road. Though it is possible to have just one scope do it all"

Upvotes: 1

Related Questions