Mysql 我应该如何根据键的参数编写case语句?

Mysql 我应该如何根据键的参数编写case语句?,mysql,ruby-on-rails,ruby,Mysql,Ruby On Rails,Ruby,例如,我有索引操作: def index if params[:query] @pharmaceutics = Pharmaceutic.where("name LIKE ?", params[:query]) elsif params[:code] @pharmaceutics = Pharmaceutic.where("barcode LIKE ?", params[:code]) else @pharmaceutics = P

例如,我有索引操作:

  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
当我发送两个参数:code和query时,我想使用这两个参数过滤我的药剂学。我有MySQL数据库。

我可能会使用如下方法:

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(…)
,以使代码更清晰。

我可能会使用如下方法:

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(…)
,以使代码更清晰。

@regedarek在Rails 4中您可以使用
Pharmaceutic.all
,如下所示:@regedarek在Rails 4中您可以使用
Pharmaceutic.all
,如下所示: