Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord find starts with

Really simple question - how do I do a search to find all records where the name starts with a certain string in ActiveRecord. I've seen all sorts of bits all over the internet where verbatim LIKE SQL clauses are used - but from what I've heard that isn't the 'correct' way of doing it.

Is there a 'proper' Rails way?

like image 836
robintw Avatar asked Oct 30 '08 19:10

robintw


2 Answers

If you're looking to do the search in the database then you'll need to use SQL.

And, of course, you'll need to do the search in the database otherwise you need to load all the objects into Ruby (which isn't a good thing).

So, you will need something like

MyModel.find(:all, :conditions => ["field LIKE ?", "#{prefix}%"]) 

where prefix is a variable with the string you're looking for.

In Rails 3.0+ this becomes:

MyModel.where("field LIKE :prefix", prefix: "#{prefix}%") 
like image 110
Gareth Avatar answered Oct 11 '22 02:10

Gareth


I would highly recommend the Searchlogic plugin.

Then it's as easy as:

@search = Model.new_search(params[:search]) @search.condition.field_starts_with = "prefix" @models = @search.all 

Searchlogic is smart enough, like ActiveRecord, to pick up on the field name in the starts_with condition. It will also handle all pagination.

This method will help prevent SQL injection and also will be database agnostic. Searchlogic ends up handling the search differently depending on the database adapter you're using. You also don't have to write any SQL!

Searchlogic has great documentation and is easy to use (I'm new to Ruby and Rails myself). When I got stuck, the author of the plugin even answered a direct email within a few hours helping me fix my problem. I can't recommend Searchlogic enough...as you can tell.

like image 45
Owen Avatar answered Oct 11 '22 01:10

Owen