使用重复值编写Ruby Hash而不重复值

时间:2014-09-10 16:13:28

标签: ruby-on-rails ruby

我在rails控制器中有以下代码:

@users = User.where(["first_name = :first_name or
                    last_name = :last_name or
                    company = :company",
                    { first_name: term, last_name: term,
                    company: term }])

期限为term = params[:search]

我不喜欢我重复term

{ first_name: term, last_name: term,
                        company: term }

有没有干燥的方法来实现这一目标?

谢谢!

2 个答案:

答案 0 :(得分:6)

你可以这样做:

@users = User.where("first_name = :term OR
  last_name = :term OR company = :term", term: term)

答案 1 :(得分:2)

您可以使用哈希语法设置参数

users = User.where('first_name = :term OR 
                    last_name = :term OR
                    company = :term', 
  term: term)