我有两个模型:ScheduledCourse 和 ScheduledSession。
scheduled_course has_many scheduled_sessions
scheduled_session belongs_to scheduled_course
ScheduledCourse 有一个虚拟属性...
def start_at
s = ScheduledSession.where("scheduled_course_id = ?", self.id).order("happening_at ASC").limit(1)
s[0].happening_at
end
... start_at 虚拟属性检查属于 ScheduledCourse 的所有 ScheduledSession 并选择最早的一个。所以 start_at
是第一次 session 发生的日期。
现在我需要在 Controller 中写入,以便只获取从今天开始到 future 的记录。我还需要编写另一个只获取过去类(class)的查询。
我无法执行以下操作,因为 start_at
是一个虚拟属性
@scheduled_courses = ScheduledCourse.where('start_at >= ?', Date.today).page(params[:page])
@scheduled_courses = ScheduledCourse.where('start_at <= ?', Date.today)
SQLite3::SQLException: no such column: start_at: SELECT "scheduled_courses".* FROM "scheduled_courses" WHERE (start_at >= '2012-03-13') LIMIT 25 OFFSET 0
最佳答案
您不能对不在数据库中的列执行 SQL 查询。如果您打算对其进行查询而不是假列,则应考虑将其设为真正的数据库列;但是如果你想从这个集合中选择项目,你仍然可以这样做。您只需在 Ruby 中完成即可。
ScheduledCourse.page(params).find_all {|s| s.start_at >= Date.today}
关于ruby-on-rails - Rails 3. 如何通过虚拟属性执行 "where"查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9686426/