通过rails查询has_many

时间:2016-02-01 08:05:43

标签: ruby-on-rails activerecord associations

协会

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

我希望在任何特定日期等内的users中获取所有Campaign 意思是,我想做的事情如下:  Campaign.first.users.where(?)

现在,当我查询:

Campaign.first.users.all

我获得了某个广告系列中所有用户的列表,但我如何才能获得仅在特定日期范围之间拥有广告系列的用户。

3 个答案:

答案 0 :(得分:2)

只需在User中定义范围,就像这样:

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

然后使用它:

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

使它成为通用&amp;总是这样!

答案 1 :(得分:1)

你有没有尝试过:

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

答案 2 :(得分:1)

  

我希望在任何特定日期内让广告系列中的所有用户

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)

-

更新 - 似乎PGSQL需要timestamp来评估日期:

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

区别在于Date&amp; Time个对象。