davegson
davegson

Reputation: 8331

where more columns equal one value

I've got this repetitive query:

Model.where(:foo1 => "bar", :foo2 => "bar", :foo3 => "bar", ..., :foo9 => "bar")

I wondered if there was a nice way to shorten the code, similar to the opposite case:

Model.where(:foo => ["bar1, bar2, bar3, ..., bar9"])

Is this possible?

Upvotes: 0

Views: 33

Answers (2)

twonegatives
twonegatives

Reputation: 3438

Another option besides sql suggestion would be to use inject method:

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

Upvotes: 0

MinhD
MinhD

Reputation: 1810

In SQL. You can:

WHERE foo1 = foo2 = foo3 = ..... = foo9 = 'bar'

So you can try:

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

More or less: demo

Upvotes: 1

Related Questions