ruby on rails named scopes (searching)
I have a named scope (name) combination of first and last name and I'm wanting to use this in a search box.
I have the code below:
named_scope :full_name, lambda { |fn| {:joins => :actor, :conditions => ['first_name LIKE ? OR second_name LIKE ?', "%#{fn}%", "%#{fn}%"]} }
def self.sea开发者_C百科rch(search)
if search
self.find(:all, :conditions => [ 'full_name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
but this doesn't work as it gives the following error:
SQLite3::SQLException: no such column: full_name: SELECT * FROM "actors" WHERE (full_name LIKE '%eli dooley%')
Thanks in advance
Houlahan
Try this:
def self.search(search)
if search
self.full_name(search)
else
find(:all)
end
end
The named scope does not add a column to the database, but an easily accessible way to get records without typing conditions every time.
It doesn't work because the :conditions
hash in the statement:
self.find(:all, :conditions => ['full_name LIKE ?', "%#{search}%"])
—is looking for an actual column named full_name
in the database table. Named scopes (simply called scopes in Rails 3) get implemented as class methods on the model, so instead you need to do this:
self.full_name(search)
- Ryan Bates has a nice Railscast on named scopes that you might find useful
Have you looked at Searchlogic?
I highly recommend it.
http://github.com/binarylogic/searchlogic
精彩评论