如何在Rails上通过动态条件查找数据?

时间:2014-12-10 03:31:04

标签: ruby-on-rails rails-activerecord

我现在正在使用Rails 3.2.13。

我制作了这个方法:

def search
  search_conditions = []
  search_conditions << ["id = ?", params[:id]] if params[:id] != ''
  search_conditions << ["name LIKE ?", "%#{params[:name]}%"] if params[:name] != ''
  @users = User.find(:all, :conditions => search_conditions)
end

但结果是:

undefined method `%' for ["name LIKE ?", "%tes%"]:Array

我不能以一种很好的方式设置多个条件吗?

2 个答案:

答案 0 :(得分:1)

由于您使用的是Rails 3.2,因此应切换到使用AREL语法。那里有很多教程。它使构建这些类型的查询更直观,更简单。使用AREL时,可以在查询中链接多个where语句。

答案 1 :(得分:1)

这样的事情:

def search
  re = Outlet.where( 1 ) 
  re = re.where( "id = ?", params[:id] ) if params.has_key? :id
  re = re.where( "name LIKE ?", "%#{params[:name]}%" ) if params.has_key? :name
  # chain it further as required...

  re.all 
end

正如前面提到的JC Avena所说,最好使用Rails 3“where(...)”语法而不是“find(:all,...)”

相关问题