Sql 其中多个列等于一个值

Sql 其中多个列等于一个值,sql,ruby-on-rails,activerecord,Sql,Ruby On Rails,Activerecord,我有一个重复的问题: Model.where(:foo1 => "bar", :foo2 => "bar", :foo3 => "bar", ..., :foo9 => "bar") 我想知道是否有一种很好的方法来缩短代码,类似于相反的情况: Model.where(:foo => ["bar1, bar2, bar3, ..., bar9"]) 这可能吗?在SQL中。你可以: WHERE foo1 = foo2 = foo3 = ..... = foo9 =

我有一个重复的问题:

Model.where(:foo1 => "bar", :foo2 => "bar", :foo3 => "bar", ..., :foo9 => "bar")
我想知道是否有一种很好的方法来缩短代码,类似于相反的情况:

Model.where(:foo => ["bar1, bar2, bar3, ..., bar9"])
这可能吗?

在SQL中。你可以:

WHERE foo1 = foo2 = foo3 = ..... = foo9 = 'bar'
因此,您可以尝试:

Model.where("foo1 = foo2 = foo3 = foo4 = foo5 = foo6 = foo7 = foo8 = foo9 = ?", "bar")

或多或少:

除了sql建议之外的另一个选项是使用
inject
方法:

query = [:foo1, :foo2, :foo3].inject({}){|hash, key| hash[key] = "bar"; hash}
# => {:foo1=>"bar", :foo2=>"bar", :foo3=>"bar"}
Model.where(query)

谢谢,好的。是否也可以对
子句执行类似操作?iE:
.where(“foo1='bar'或foo2='bar'…或foo9='bar'”)
当您使用
时。where
这样,第一个参数是SQL。所以,是的,你可以和,或者,不,或者任何你想做的事情。对于OR子句,你可以尝试IN子句的倒装:
Model。其中(“'bar'IN(foo1,foo2,foo3,…,foo8)”)