Peter Blomgren
Peter Blomgren

Reputation: 47

Query to find "active" ads in Rails

I'm building an ad manager that has the following Schema:

<Campaign id: nil, target_id: nil, date_view_based: nil, start_date: nil, end_date: nil, max_views: nil, cur_views: nil, link_to: nil, alt_data: nil, title_attr: nil, created_at: nil, updated_at: nil, user_id: nil, image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil, link_clicked: nil, name: nil>

What I need is a way to create a method that will run like this...

Campaigns.current?

And output an array of something like this

Campaign.where('date_view_based =? AND end_date >= ? AND start_date <= ?', "Date", Date.today.strftime('%m/%d/%Y'), Date.today.strftime('%m/%d/%Y')).concat(Campaign.where('date_view_based = ? AND max_views >= ?, "View", :cur_views))

However, the Campaign.where('max_views >= ?, :cur_views) doesn't work, so how can I compare these two attributes? Surely there must be a better way to do this any suggestions would be appreciated.

Sorry I thought I had included the structure but I guess I didn't: Campaign.new returns:

#<Campaign id: nil, target_id: nil, date_view_based: nil, start_date: nil, end_date: nil, max_views: nil, cur_views: nil, created_at: nil, updated_at: nil, name: nil>

Upvotes: 0

Views: 45

Answers (1)

railscard
railscard

Reputation: 1848

How about this?

class Campaign < ActiveRecord::Base

  # ...

  def self.current
    date_view_based_enum = %W(Date View)
    date = Date.today.strftime('%m/%d/%Y')
    where("((start_date <= ? AND end_date >= ?) OR (max_views >= cur_views)) AND date_view_based IN (?)", date, date, date_view_based_enum)
  end
end

Upvotes: 1

Related Questions