views:

15

answers:

2

Hi,

I have the following models:

class Campaign < ActiveRecord::Base
  has_many   :campaign_keywords
  has_many   :leads, :through => :campaign_keywords
end

class CampaignKeyword < ActiveRecord::Base
  belongs_to :campaign
  has_many   :leads
end

class Lead < ActiveRecord::Base
  belongs_to :campaign_keyword
end

I am trying to build a function in the "Campaign" model that will only return leads which belong to a given campaign_keyword.

My attempt is:

def leads?(campaign_keyword_id = -1)
  self.leads :conditions => ['campaign_keyword_id = #{campaign_keyword_id}']
end

but this does not work, the conditions are ignored.

Can you see a solution to this?

A: 

Try this:

def leads?(campaign_keyword_id = -1)
  self.leads.all :conditions => ['campaign_keyword_id = #{campaign_keyword_id}']
end

I would rewrite your query as follows:

def leads?(campaign_keyword_id = -1)
  self.leads.all :conditions => ['campaign_keyword_id = ?', campaign_keyword_id]
end

OR

self.leads.find_all_by_compaign_keyword_id(campaign_keyword_id)
KandadaBoggu
Its still ignoring the :conditions arguments.SQL generated is:SELECT `leads`.* FROM `leads` INNER JOIN `campaign_keywords` ON `leads`.campaign_keyword_id = `campaign_keywords`.id WHERE ((`campaign_keywords`.campaign_id = 1))
Jason
Did you try the second option?
KandadaBoggu
+1  A: 

Create a named_scope for your Lead model, like so:

class Lead < ActiveRecord::Base
  belongs_to :campaign_keyword

  named_scope :with_keyword, lambda { |keyword| { :conditions => { :campaign_keyword => keyword } } }
end

Now, when you want to get leads for a particular campaign keyword, you would do so like this:

def leads_for_campaign(keyword)
  self.leads.with_keyword(keyword)
end

This is much nicer and more re-usable, because the Lead model itself now knows how to find leads for a specific campaign.

For more of an idea of what you can do with named_scopes, check out http://apidock.com/rails/ActiveRecord/NamedScope/ClassMethods/named_scope

Chris
Very elegant solution, thanks Chris!
Jason