Haseeb Ahmad
Haseeb Ahmad

Reputation: 8730

Query for has_many through rails

Association is

class Campaign
  has_many :views_logs
  has_many :users, through: :views_logs
end

I want to get all users in a Campaign within any specific dates etc meaning, I want to do something like: Campaign.first.users.where(?)

Now, when I query:

Campaign.first.users.all

I get list of all users within a certain campaign, but how I can I get only those users which have Campaign between specific date ranges only.

Upvotes: 0

Views: 388

Answers (3)

Richard Peck
Richard Peck

Reputation: 76774

I want to get all users in a Campaign within any specific dates

ActiveRecord Association Extension:

#app/models/campaign.rb
class Campaign < ActiveRecord::Base
   has_many :users, through: :view_logs do
      def between start_date, end_date
         where(created_at: start_date..end_date)
      end
   end
end

@campaign = Campaign.find x
@users    = @campaign.users.between(Date.today - 2, Date.today.day)

--

Update - it seems PGSQL requires a timestamp to evaluate dates:

@users = @campaign.users.between(Time.now.midnight - 2.days, Time.now.midnight)

The difference being that between Date & Time objects.

Upvotes: 1

Hieu Pham
Hieu Pham

Reputation: 6707

Simply define a scope in User like this:

class User < ActiveRecord::Base
  # Your current code
  scope :during_campaign, -> (start, end) { 
       joins(view_logs: :campaign).where('campaigns.created_at >= ? AND campaigns.created_at <= ?', start, end)
  }

end

Then use it:

# User from yesterday compaign for eg
User.during_campaign(1.day.ago, Time.now)

Make it generic & pretty always!

Upvotes: 2

aliibrahim
aliibrahim

Reputation: 1965

Have you tried doing:

Campaign.first.users.where("campaigns.created_at > #{start_date} AND campaigns.created_at < #{end_date}")

Upvotes: 1

Related Questions