Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do "like" queries with ActiveRecord in Rails 2.x and 3.x?

I'm doing queries like this in Rails 3.x

Speaker.where("name like '%yson%'")

but I'd love to avoid the DB specific code. What's the right way to do this?

If there's a way to do this in Rails 2.x too, that would help too.

like image 796
Dan Rosenstark Avatar asked Mar 16 '11 18:03

Dan Rosenstark


People also ask

What is ActiveRecord :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module... ActiveRecord is defined as a module in Rails, github.com/rails/rails/tree/master/activerecord/lib/…

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is pluck in Ruby?

Ruby. 2018-05-09 · 2 min read. In Rails, pluck is a shortcut to select one or more attributes without loading the corresponding records just to filter out the selected attributes. It returns an Array of attribute values.


1 Answers

In Rails 3 or greater

Speaker.where("name LIKE ?", "%yson%")

In Rails 2

Speaker.all(:conditions => ["name LIKE ?", "%yson%"])

Avoid to directly interpolate strings because the value won't be escaped and you are vulnerable to SQL injection attacks.

like image 160
Simone Carletti Avatar answered Sep 20 '22 13:09

Simone Carletti