So what you want is to measure the efficiency of a campaign, and have data about the customers that came back after the campaign and did purchases.
I propose:
class Campaign
def next_visits
# Wrapping the whole code of this method in @next_visits will perform local caching
# There is a good railscast that explain it in details (5 minutes long video)
# You can see it there: http://railscasts.com/episodes/1-caching-with-instance-variables
@next_visits ||= begin
# This will be the starting date of "next visits"
since = self.end_of_campaign # I assume you can get the TimeDate of the end of campain
# List of ids of customers that participated to the campaign
customers_ids = self.visits.uniq(:customer_id).pluck(:customer_id)
# Return the visit records
next_visits = Visit.where(purchase_flag: true, customer_id: customers_ids)
next_visits.where('created_at > ?', since).first
end
end
end
Then you call Campaign.find(123).next_visits
EDIT
You should use correct TZ with the variable since
About @next_visits ||= begin ... end
: This is a caching technique. First time you call the method, all the code inside the begin
blok will be executed, and the result (the records) will be stored in the instance variable @next_visits and returned to the caller.
Next time you call the method, the cached result stroed in @next_visits will be directly returned without hitting your database. That is good for performance.
More info about that http://railscasts.com/episodes/1-caching-with-instance-variables