Ruby on Rails,通过两个条件查找 [英] Ruby on Rails, find by two conditions
本文介绍了Ruby on Rails,通过两个条件查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下模型:
我试图通过两个字段的组合来查找给定模型的所有值。
create_tableusers,:force => true do | t |
t.stringname
t.stringurl
t.integerclicks_given
t.integerclicks_received
t.datetimecreated_at
t.datetimeupdated_at
end
我定义了这个方法对于模型:
def credits
credits = self.clicks_given - self.clicks_received
end
我正在尝试查找给定信用点以上的所有用户:
@users = User.find(:all,:conditions => {credits> =?,-5})
和:
@users = User .find(:all,:conditions => {clicks_given - clicks_received> =?,-5})
失败。为了找到合适的用户,正确的语句应该是什么?
解决方案
传递条件作为数组而不是散列:
@users = User.find(:all,:conditions => [clicks_given - clicks_received> =?, 5])
由于credits不是数据库列,所以第一个版本将不起作用。
编辑:
或者在Rails 3语法中,用你的命令:
@users = User.where(clicks_given - clicks_received> =?,5).order(clicks_given - clicks_received)
I am trying to find all values of a given model by a combination of two fields.
I have the following model:
create_table "users", :force => true do |t|
t.string "name"
t.string "url"
t.integer "clicks_given"
t.integer "clicks_received"
t.datetime "created_at"
t.datetime "updated_at"
end
and I have defined this method for the model:
def credits
credits = self.clicks_given - self.clicks_received
end
I am trying to find all users above a given credits:
@users = User.find(:all, :conditions => { "credits >= ?", -5 })
and:
@users = User.find(:all, :conditions => { "clicks_given - clicks_received >= ?", -5 })
Fail. What should is the correct statement to to find the right users?
解决方案
Pass the condition as an array instead of a hash:
@users = User.find(:all, :conditions => [ "clicks_given - clicks_received >= ?", -5 ])
The first version will not work since "credits" is not a database column.
EDIT:
Or in Rails 3 syntax, with your order:
@users = User.where("clicks_given - clicks_received >= ?", 5).order("clicks_given - clicks_received")
这篇关于Ruby on Rails,通过两个条件查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文