views:

42

answers:

1

I have a named_scope in rails that finds episodes by there directors given name

  named_scope :director_given, lambda { |dr| {:joins => :director, :conditions => ['given = ?', dr]} }

It works great but I would like it to also work on substrings one the name. e.g. instead of having to search for 'Lucy' you could just search 'Lu'.

P.S. I also have another named scope which does exactly the same thing but on the directors last name. It there a way to combine the two?

Thanks,

+2  A: 

Something like

named_scope :director_given, lambda { |dr| {:joins => :director, :conditions => ['given LIKE ?', "%#{dr}%"]} }

Second question:

named_scope :director_given, lambda { |dr| {:joins => :director, :conditions => ['first_name LIKE ? OR second_name LIKE ?', "%#{dr}%", "%#{dr}%"]} }
Vlad Zloteanu
Thanks, I tried this but when try to use it in the console i get this error: ActiveRecord::StatementInvalid: SQLite3::SQLException: near "%": syntax error: SELECT "episodes".* FROM "episodes" INNER JOIN "people" ON "people".id = "episodes".director_id AND ("people"."type" = 'Director' ) WHERE (given = %'Lucy'%) I tried changing the = to LIKE but I just get the same error
Philb28
Updated my response.
Vlad Zloteanu
Thanks, works great!!Cheers!
Philb28
Just a matter of style: named_scope :director_given, lambda { |dr| {:joins => :director, :conditions => ['first_name LIKE :dr OR second_name LIKE :dr', :dr => "%#{dr}%"]} }It is trivial in this example but it can become handy if you have several params used several times each.
Fer