简体   繁体   中英

Ruby on rails where() with a method

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM