ruby on rails - How would I create an activerecord scope(s) that would return customers who's next visit resulted in a purchase -
i have 3 activerecord models: customer, visit , campaign.
customer has_many :visits visit belongs_to :customer campaign has_many :visits the visit model tracks everytime particular customer visits website, pages visited, ads displayed , importantly if made purchase. campaign series of ads customers see during there visits site. each campaign lasts 1 hour (24 campaigns day) , has many visits.
what i'm trying develop activerecord scopes or class methods enable me identify "next visit purchases".
for example, on july 4th fourth campaign of day had 100 visits customers. want able @ next visit each of customers , identify visits/customers had/made purchase on next visit. i'm finding difficult wrap mind around customers subsequent visits aren't on same day, yet want identify "next visit" , resulted in purchase.
what envisioned like:
campaign.find(2232).next_visit.purchase #where next_visit , purchase scopes or
visit.find(5445).next_visit.purchase i have purchase flag in visits model purchase scope straight forward.
scope, :purchase, where(:purchase_flag => true) also based on railscast #215, if create scope on visits model can use joins , merge apply them customer , campaign models.
campaign.joins(:visits).merge(visit.purchase) is correct approach? if so, how define next scope , if not, suggest alternative approach.
update: i've gotten great responses. curious know if general consensus deepak's approach on point or other responses preferable.
so want measure efficiency of campaign, , have data customers came after campaign , did purchases.
i propose:
class campaign def next_visits # wrapping whole code of method in @next_visits perform local caching # there railscast explain in details (5 minutes long video) # can see there: http://railscasts.com/episodes/1-caching-with-instance-variables @next_visits ||= begin # starting date of "next visits" since = self.end_of_campaign # assume can timedate of end of campain # list of ids of customers participated campaign customers_ids = self.visits.uniq(:customer_id).pluck(:customer_id) # return visit records next_visits = visit.where(purchase_flag: true, customer_id: customers_ids) next_visits.where('created_at > ?', since).first end end end then call campaign.find(123).next_visits
edit
you should use correct tz variable since
about @next_visits ||= begin ... end: caching technique. first time call method, code inside begin blok executed, , result (the records) stored in instance variable @next_visits , returned caller.
next time call method, cached result stroed in @next_visits directly returned without hitting database. performance.
more info http://railscasts.com/episodes/1-caching-with-instance-variables
Comments
Post a Comment