valachi221
valachi221

Reputation: 23

How to apply scopes to joins in rails?

Let's say i've established this associations:

class Budget
  has_many :forfeitures
  scope :with_forfeitures, ->{ joins(:forfeitures) }
end

class Forfeiture
  belongs_to :budget      
  scope :between, ->(from, to) { where("created_at > ? AND created_at < ?", from, to)}
end

Now i can do this:

Budget.with_forfeitures.where("forfeitures.created_at > ? AND forfeitures.created_at < ?", from_date, to_date)

But notice that i had to write my between scope in raw sql.

Can i instead do something like Budget.with_forfeitures.between(from_date, to date) but in that way that between applies to forfeitures? If i can't do that, how do i achieve the same result without duplicating my between scope in raw sql?

Upvotes: 1

Views: 370

Answers (1)

denis-bu
denis-bu

Reputation: 3446

I'd try to write Budget.joins(:forfeitures).merge(Forfeiture.between(from, to))

So, merge method should work for you.

I'd suggest you to watch episode 215 and episode 239 from railscasts.com

Upvotes: 1

Related Questions