Dan Mitchell
Dan Mitchell

Reputation: 864

Model scope from association method

I'm trying to create a scope for future events only, the date of an event is based on the activities date and I have a method in my events model called end_at but when trying to create a scope for my controller I am getting

PG::UndefinedColumn: ERROR:  column "end_at" does not exist

Event model

has_many :activities, dependent: :destroy

scope :future_events, -> { where('end_at >= ?', Date.today) }

def end_at
  activities.chronological.last.end_at
end

Upvotes: 0

Views: 82

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

It is impossible to query by methods. You can do something like this:

scope :future_events, lambda {
  joins(activities: :chronological)
    .where('chronologicals.end_at >= ?', Date.today)
}

Description:

  • in joins you put names of associations;
  • in where you put the real names of tables how they are named in database (they sometimes happen to be different from model's associations names).

This scope is basically saying that you want to return future events, where its activities's chronological's end_at attribute is >= Date.today.

Upvotes: 2

Related Questions