Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Is there a `AR#or_where`?

Is there a AR#or_where in Rails 3 as in

User.where(cond1).or_where(cond2)

?

like image 204
Andrei S Avatar asked Feb 26 '23 13:02

Andrei S


2 Answers

There isn't a method like that in Rails.

I think that the easiest way to do an OR in a WHERE clause is to do something like this:

User.where("first_name = ? OR last_name = ?", params[:first_name], "Wilson")

If you want to learn the Arel methods (which does have an "or" method), look here: https://github.com/rails/arel#readme. Using Arel and ActiveRecord, you can do the same thing like this:

User.where(User.arel_table[:first_name].eq(params[:first_name]).or(User.arel_table[:last_name].eq('Wilson')))
like image 157
dontangg Avatar answered Mar 08 '23 08:03

dontangg


You can take a look at meta_where. This gem allows more powerful ActiveRecord query expressions in Ruby code, without requiring dropping to SQL fragments.

like image 20
yfeldblum Avatar answered Mar 08 '23 09:03

yfeldblum