Reputation: 1348
I want to perform a where() query, on a method of a model. How to I do this?
If I can't, is there any way I can do this:
Session.find_each.select do |session|
session.end_date > params[:date_from].to_date && session.end_date < params[:date_to].to_date
end
But returning an ActiveRecordRelation instead of an Array?
session.rb
class Session < ActiveRecord::Base
belongs_to :course
delegate :units, to: :course
def end_date
start_date + units.count.weeks
end
end
end_date
is the method, but start_date
is a field.
Upvotes: 0
Views: 3725
Reputation: 7579
You can, but you'll have to use joins
units
belongs to course, so you'll have to join courses
table before applying where
. Otherwise, your fetch all sessions, and filter one by one based on end_date
, which will generate a lots sql queries.
Session.joins(:course).where("calculate_end_date() > ? AND calculated_end_date() < ?", date, date)
you'll need to calculate end date
use sql functions, google it
Upvotes: 2