开发者

Rails - Find Condition of two model fields

开发者 https://www.devze.com 2023-01-03 08:12 出处:网络
I\'m trying to find the results of a model where it queries as the result of two conditions. I have a search tag that looks for

I'm trying to find the results of a model where it queries as the result of two conditions.

I have a search tag that looks for

 Model.find(:all, :conditions => "name LIKE params[search]")

but I'd like for the search to find all records where "name LIKE params[search] or descript开发者_如何学Goion LIKE params[search] .

Is there any way to add an OR into a condition in rails?

or should I make an if statement?


For Rails 2.x you can use this query, which isn't vulnerable to SQL injection attacks:

Model.all(:conditions => ["name LIKE ? OR description LIKE ?",
  "%#{params[:search]}%", "%#{params[:search]}%"])
  • See Active Record Query Interface, section 2.1 for further information


In RAILS 2.3 (uses parameters instead of pure SQL code for help with injection)

Model.all(:conditions=>['name LIKE ? OR name like ?','%'+@term_one+'%', '%'+@term_two+'%'])

I also really like to use Condition Builder for ActiveRecord in RAILS 2.x projects, because you can do:

Condition.block{|c|
  c.and :published, true
  c.and {|d|
    d.or :full_text, "LIKE", "%#{options[:qs]}%" 
    d.or :full_text, "LIKE", "%#{options[:qs]}%" 
  }
end

Note: Postgres users should use ILIKE (case insensitive like) instead of LIKE.

Note 2: Rails 3.0 would use the where clause chaining, which is pretty cool, and should have an OR operator added soon ActiveRelation GitHub -- but it'll look like User.where(:name => 'bob').or(:name=>'same')


Model.find(:all, :conditions => "name LIKE '%#{params[:search]}%' OR description like '%#{params[:search]}%'")

this might work for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消