Ruby on rails 循环变量的Rails

Ruby on rails 循环变量的Rails,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有以下developers\u controller,我想基于location\u参数执行查询 在index_update操作中,我创建了一个变量location,其中包含用户为研究提供的location_参数。我想在此变量上执行每个循环,以根据用户请求过滤@locations=Location.all中的数据 这是我的私有方法位置参数: def location_params params.require(:location).permit(:country, :location, :s

我有以下
developers\u controller
,我想基于
location\u参数执行查询

index_update
操作中,我创建了一个变量
location
,其中包含用户为研究提供的
location_参数。我想在此变量上执行
每个
循环,以根据用户请求过滤
@locations=Location.all中的数据

这是我的私有方法
位置参数

def location_params
  params.require(:location).permit(:country, :location, :surfspot, :barbecue, :villa, :swimmingpool, :skiresort, :singleroom )
end
这是我的
索引更新
操作:

def index_update
  location = Location.new(location_params)
  locations = Location.all
  location.each do |param, value|
    if value != nil
      locations = locations.where(param => value)
    end
  end
end
我找不到如何循环
位置
变量


这是我在Rails控制台中的位置模型:

=> #<Location:0x000000036b6838
 id: nil,
 host_id: nil,
 description: nil,
 location: nil,
 singleroom: nil,
 sharedroom: nil,
 surfspot: nil,
 barbecue: nil,
 villa: nil,
 swimmingpool: nil,
 skiresort: nil,
 created_at: nil,
 updated_at: nil,
 country: nil,
 state: nil,
 houseimages: nil

=>#如果您可以
位置参数
实例化一个新位置,那么它们很可能已经是传递到
的正确格式,其中

def index_update
  locations = Location.where(location_params)
end
如果需要从参数中删除nil值:

def index_update
  locations = Location.where(location_params.delete_if { |k,v| v.nil? })
end

我将这样做,以便在查询中仅使用具有当前值的参数:

def index_update
  query_attributes = location_params.select { |_, v| v.present? }
  locations = Location.where(query_attributes)
end
或:


你的实际问题是什么?循环或div的宽度?而不是
if值!=无
使用
if!value.nil?
。您不应该在
位置
上循环,而不是
位置
?城市
从哪里来,它不在
位置参数
中?原始参数看起来怎么样,
Location
看起来怎么样?预期输出是什么?@theTinMan或
除非value.nil?
,或者更好的是,
如果value.present?
。问题是如果一些
Location\u参数
等于
nil
,然后查询将只选择那些字段为空的条目。虽然我不想在值为
nil
时添加过滤器,但基本上我想返回给定参数的所有结果,这就是为什么我想做一个循环并使用
if值。present?
条件,但这个答案确实非常好,谢谢!
def index_update
  query_attributes = location_params.reject { |_, v| v.blank? }
  locations = Location.where(query_attributes)
end