模式
create_table "events", force: :cascade do |t|
t.string "title"
t.text "description"
t.date "date"
t.boolean "close"
end
event.rb
scope :expired_or_closed_events, -> {where(['close = ? OR close IS ?', true] || ['date < ?', Date.current])}
我尝试了上述范围,但我得到以下错误
2.3.0 :014 > events.expired_or_closed_events
ActiveRecord::PreparedStatementInvalid: wrong number of bind variables (1 for 2) in: close = ? OR close IS ?
有人可以告诉我如何正确地写这个范围
答案 0 :(得分:3)
你的范围应该是:
scope :expired_or_closed, -> { where("close = true OR date < ?", DateTime.now) }
或使用Arel
scope :expired_or_closed, -> { where(arel_table[:close].eq(true).or(arel_table[:date].lt(DateTime.now)) }
请注意,我使用expired_or_closed
而不是expired_or_closed_events
,因为我们在事件模型中使用`events&#39;来定义此范围。是多余的。
答案 1 :(得分:3)
使用此
scope :expired_or_closed_events, -> { where( "close == ? || date < ? ", true, Date.current ) }
I think your condition should be **close == ? **
otherwise no sense of condition, which always calculate as true