Ruby on rails 查询';任何';带'的值;其中';在轨
我有以下方法:Ruby on rails 查询';任何';带'的值;其中';在轨,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,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 问题是,如果我的状态为空,我将返回一个空数组。因此,我想将我的state参数设置为默认值,类似于“any”,这将跳过where(state…)查询,直接转到joins。大概
def self.fetch_by_subcat(subcat_id, state)
where(state: state).joins(:subcategories).where("subcategory_id = ? AND published = ?", subcat_id, true)
end
问题是,如果我的状态为空,我将返回一个空数组。因此,我想将我的state参数设置为默认值,类似于“any”,这将跳过where(state…)查询,直接转到joins。大概是
def self.fetch_by_subcat(subcat_id, state='any')
where(state: state).joins...
end
有办法吗?试图避免if/else 您可以像这样构建作用域:
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
还有另一种方法:
def self.fetch_by_subcat(subcat_id, state = 'state')
joins(:subcategories).where("subcategory_id = ? AND published = ? AND state = #{state}", subcat_id, true)
end
它是如何工作的?若您传递状态,那个么它只是简单地插入。如果不是,查询将如下所示:WHERE table_name.state=table_name.state。
这总是正确的
这里要添加的唯一内容是保护该方法不受sql注入的影响,并只传递特定的、允许的状态值