0

For example I have index action:

  def index
    if params[:query]
      @pharmaceutics = Pharmaceutic.where("name LIKE ?", params[:query])
    elsif params[:code]
      @pharmaceutics = Pharmaceutic.where("barcode LIKE ?", params[:code])
    else
      @pharmaceutics = Pharmaceutic.all
    end
  end

And when I send two params: code and query I would like to filter my Pharmaceutics using both of them. I have MySQL database.

4

1 回答 1

4

我可能会使用scoped这样的方法:

def index
  scope = Pharmaceutic.scoped # Pharmaceutic.all if you use Rails 4
  scope = scope.where('name LIKE ?', params[:query]) if params[:query].present?
  scope = scope.where('barcode LIKE ?', params[:code]) if params[:code].present?
  @pharmaceutics = scope
end

您还可以编写自定义范围并where(...)用它们替换以使代码更清晰。

于 2013-07-25T09:19:25.907 回答