Adding more than one string to a controller find condition?

别来无恙 提交于 2019-12-25 09:01:14

问题


I have the following code in one of my Rails (3.1) controllers:

@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

They are all working as expected, but I am trying to somehow merge two of them together so it shows the count of calls created in the last 1 day, but only for calls with a destination that matches the current users destination_id value.

I have tried to add :condition but with no joy:

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

Is it possible to add more than one condition in this way? If so, how?


回答1:


Where creates a scope and scopes can be chained, so you can do

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



回答2:


Try this:

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


来源:https://stackoverflow.com/questions/8862065/adding-more-than-one-string-to-a-controller-find-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!