我想知道如何根据params是否存在来成功设置动态Active Record查询。
我有这个查询
Animal.joins(:user).where(animal_type: params[:animal_type], rehomed: params[:rehomed], users: {town: params[:animal_town]})
我已经尝试了这些方面的东西,但我的语法都错了,我相信:
conditions = []
conditions << [ animal_type: params[:animal_type], ] if params[:animal_type].present?
conditions << [ rehomed: params[:rehomed], ] if params[:rehomed].present?
conditions << [ users: {town: params[:animal_town]} ] if params[:animal_town].present?
@animals = Animal.joins(:user).where(conditions)
我不想把它全部放在嵌套的哈希中,是吗?
答案 0 :(得分:4)
你必须这样做:
conditions = {}
conditions.merge!(animal_type: params[:animal_type]) if params[:animal_type].present?
conditions.merge!(rehomed: params[:rehomed]) if params[:rehomed].present?
conditions.merge!(users: {town: params[:animal_town]}) if params[:animal_town].present?
@animals = Animal.joins(:user).where(conditions)
答案 1 :(得分:2)
我会做这样的事情:
scope = Animal.joins(:user)
scope = scope.where(animal_type: params[:animal_type]) if params[:animal_type].present?
scope = scope.where(rehomed: params[:rehomed]) if params[:rehomed].present?
scope = scope.where(users: { town: params[:animal_town] }) if params[:animal_town].present?
@animals = scope
进一步改进:将范围的构建移动到Animal模型中的方法:
# in controller
@animals = Animal.find_by_query(params.slice(:animal_type, :rehomed, :animal_town))
# in Animal model
def self.find_by_query(query = {})
query.reject { |_, v| v.blank? }
scope = joins(:user)
scope = scope.where(animal_type: query[:animal_type]) if query[:animal_type]
scope = scope.where(rehomed: query[:rehomed]) if query[:rehomed]
scope = scope.where(users: { town: query[:animal_town] }) if query[:animal_town]
scope
end