开发者

Rails3: Searching for Users by Second nad First name?

I want to write a simple search method in my开发者_StackOverflow社区 User model where it checks agisnt the Second name and first name and returns matching users. I have this at the moment but throws an error:

  def self.search(search)
    if search
      where("first_name like ? or second_name like ?", "%#{search}%")
    else
      all
    end
  end

the error is: wrong number of bind variables (1 for 2) in: first_name like ? or second_name like ?

How can i fix this?

Thanks


You have two ? which means the where method is expecting two arguments:

def self.search(search)
  if search
    where("first_name like ? or second_name like ?", "%#{search}%", "%#{search}%")
  else
    all
  end
end

I'm not sure if you can streamline those likes to use one argument instead of the duplicate two, but you could clean it up a little:

def self.search(search)
  if search
    q = "%#{search}%"
    where("first_name like ? or second_name like ?", q, q)
  else
    all
  end
end


You can use

where("first name like :name or second name like :name", :name => "%foo%")
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜