Question: filter using join model ruby on rails

Question

filter using join model ruby on rails

Answers 2
Added at 2017-09-07 19:09
Tags
Question

I need to show posts from users who have an active subscription.

model/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

model/post.rb

belongs_to :user, dependent: :destroy

how do I do the query?

Answers to

filter using join model ruby on rails

nr: #1 dodano: 2017-09-07 19:09

Please try the below model query,

Post.joins(user: :profile).where('? BETWEEN start_suscription AND end_suscription', Date.current)
nr: #2 dodano: 2017-09-07 21:09
Post.joins(user: :profile).merge(Profile.active)

This will generate the same query as in the @mohanraj answer. But with this solution you don't have to repeat existing logic (DRY Principle).

Source Show
◀ Wstecz