过滤器使用连接模型ruby on rails

时间:2017-09-07 17:03:06

标签: ruby-on-rails activerecord rails-activerecord

我需要显示有效订阅的用户的帖子。

模型/ user.rb

has_one :profile, dependent: :destroy
has_many :posts, dependent: :destroy

model / profile.rb - > suscription

belongs_to :user, dependent: :destroy
scope :active, -> (as_of_date = Date.current) { where('? BETWEEN start_suscription AND end_suscription', as_of_date) } // return true is active

模型/ post.rb

belongs_to :user, dependent: :destroy

我该如何进行查询?

2 个答案:

答案 0 :(得分:1)

Post.joins(user: :profile).merge(Profile.active)

这将生成与@mohanraj的答案中相同的查询。但是在使用此解决方案时,您不必重复现有代码(DRY Principle)。

答案 1 :(得分:0)

请尝试以下型号查询,

Post.joins(user: :profile).where('? BETWEEN start_suscription AND end_suscription', Date.current)