在Rails中使用'where'查询'any'值

The*_* Oz 2 ruby ruby-on-rails ruby-on-rails-4

我有以下方法:

def self.fetch_by_subcat(subcat_id, state)
  where(state: state).joins(:subcategories).where("subcategory_id = ? AND published = ?", subcat_id, true)
end 
Run Code Online (Sandbox Code Playgroud)

问题是,如果我的状态为空,我会返回一个空数组.所以我想将我的state参数设置为默认值,例如'any',它将简单地跳过where(state ...)查询并直接进入连接.所以像

def self.fetch_by_subcat(subcat_id, state='any')
  where(state: state).joins...
end 
Run Code Online (Sandbox Code Playgroud)

有办法吗?试图避免if/else.

mbi*_*ard 6

您可以构建这样的范围:

def self.fetch_by_subcat(subcat_id, state)
  scope = joins(:subcategories).where("subcategory_id = ? AND published = ?", subcat_id, true)
  scope = scope.where(state: state) unless state.blank?
  scope
end
Run Code Online (Sandbox Code Playgroud)