开发者

Named scope SQL syntax error

开发者 https://www.devze.com 2023-02-28 11:13 出处:网络
Looks like I have some problems with quotes? My named scope: named_scope :find_by_name, lambda {|name| {:conditions => [\"first_name LIKE \'%?%\' or last_name LIKE \'%?%\'\",name.split(\' \').fir

Looks like I have some problems with quotes?

My named scope:

named_scope :find_by_name, lambda {|name| {:conditions => ["first_name LIKE '%?%' or last_name LIKE '%?%'",  name.split(' ').first, name.split(' ').last]}}

And here's how I'm doing a search:

find_by_name("#{search}")

And here's the generated SQL and error:

ActionView::Template::Error (Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'foo'%' or last_name LIKE '%'foo'%')' at line 1: SELECT COUNT(*) FROM `users` WHERE (first_name LIKE '%'foo'%' or la开发者_如何转开发st_name LIKE '%'foo'%')):


You can try to get rid of '%?%' in your SQL syntax and instead use this:

named_scope :find_by_name, lambda {|name| {:conditions => ["first_name LIKE ? or last_name LIKE ?",  '%' + name.split(' ').first + '%', '%' + name.split(' ').last + '%']}}

Please let me know if it works.
P.S. Also it is not good idea to define find_by_something scope, Rails alredy did it for you, ActiveRecord dynamicly defines such methods.

0

精彩评论

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