[英]Rails scope method returns WhereChain instead of array
在我的Deal
類中,我添加了一個范圍方法:
scope :current, -> { where {|d| d.end_date > Date.today} }
它返回正確的數據,但不是返回一個我可以計算,迭代等的數組,它返回一個ActiveRecord::QueryMethods::WhereChain
,我不能做任何事情。
我注意到對Deal.current
的調用以“ @scope=
”開頭:
Deal.current
Deal Load (1.0ms) SELECT "deals".* FROM "deals"
=> #<ActiveRecord::QueryMethods::WhereChain:0x00007fbc61228038
@scope=
[#<Deal:0x00007fbc5fdb2400
id: 7,
我想如果我知道如何使用“正常” where
語句進行比較(而不是相等),例如where(end_date>Date.today)
可以幫助解決我的問題,因為范圍方法使用簡單的where
語句,如scope :posted, -> { where.not(posted_date:nil) }
返回一個正常可用的ActiveRecord.Relation
,但我確實想弄清楚如何正確使用更復雜的查詢。
你可以使用如下:
scope :current, -> { where('end_date > ?', Date.today) }
Rails中不存在where
-call的塊語法。
您還可以查看arel
( https://robots.thoughtbot.com/using-arel-to-compose-sql-queries );
deal = Deal.arel_table
Deal.where(deal[:end_date].gt(Date.today))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.