【问题标题】:Adding more than one string to a controller find condition?向控制器查找条件添加多个字符串?
【发布时间】:2012-01-14 11:59:41
【问题描述】:

我的 Rails (3.1) 控制器之一中有以下代码:

@count = Call.where(:destination => current_user.destination_id).count

@count_day = Call.where('created_at > ?', 1.days.ago).count
@count_month = Call.where('created_at > ?', 30.days.ago).count

它们都按预期工作,但我试图以某种方式将其中两个合并在一起,以便显示过去 1 天创建的呼叫计数,但仅适用于目的地与当前用户destination_id 值匹配的呼叫。

我尝试添加 :condition 但没有任何乐趣:

@count_day = Call.where(:destination => current_user.destination_id, :condition ['created_at > ?', 1.days.ago]).count

是否可以通过这种方式添加多个条件?如果有,怎么做?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord controller conditional-statements


    【解决方案1】:

    试试这个:

    @count_day = Call.where("destination = :destination AND created_at > :date", { :destination => current_user.destination_id, :date => 1.days.ago}).count
    

    【讨论】:

    • 如果我使用你的代码@count_day = Call.where(:conditions=>['destination=(?) AND created_at>(?)',current_user.destination_id, 1.days.ago]).count,那么我会收到以下错误SQLite3::SQLException: no such column: calls.conditions: SELECT COUNT(*) FROM "calls" WHERE "calls"."conditions" IN ('destination=(?) AND created_at>(?)', '01772232427', '2012-01-13 12:57:40.453694')
    【解决方案2】:

    在哪里创建一个作用域,作用域可以被链接,所以你可以这样做

    Call.where(:destination =>current_user.id).where("created_at > ?", 1.day.ago).count
    

    【讨论】:

    • 由于某种原因输出#<ActiveRecord::Relation:0x132da1d48>而不是调用计数。
    • 如果你想要计数,把.count放在最后——我只是说明where可以被链接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 2016-09-08
    • 2014-05-29
    • 2021-12-11
    • 1970-01-01
    • 2021-11-28
    相关资源
    最近更新 更多