2017-03-08 242 views
-2

我有以下developers_controller,我想执行基于location_params的查询。Rails循环变量

index_update操作中,我创建了一个变量location,其中location_params作为用户给出的研究输入。我想对此变量执行each循环,以基于用户请求过滤来自@locations = Location.all的数据。

这是我的私有方法location_params

def location_params 
    params.require(:location).permit(:country, :location, :surfspot, :barbecue, :villa, :swimmingpool, :skiresort, :singleroom) 
end 

这是我index_update行动:

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 

我不能找出如何循环的location变量。


这是我的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 
+1

什么是您的实际问题?循环或div的宽度? – bork

+1

而不是'if value!= nil'使用'if!value.nil?'。 –

+1

难道你不应该循环'位置',而不是'位置'? –

回答

1

我会做这样的事情,只使用参数与当前值查询:

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

或者:

def index_update 
    query_attributes = location_params.reject { |_, v| v.blank? } 
    locations = Location.where(query_attributes) 
end 
+0

的确如此,我会接受它。谢谢。 –

0

如果可以location_params实例化一个新的位置,那么很有可能他们已经是通入where正确的格式:

def index_update 
    locations = Location.where(location_params) 
end 

如果您需要从PARAMS删除零值:

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

问题是,如果某些'location_params'等于'nil',那么查询将仅选择那些空字段的条目。虽然我不想添加该过滤器,如果该值是'nil' 基本上我想返回给定参数的所有结果,这就是为什么我正在考虑做一个循环并使用'if value.present?'条件 但的确,这个答案非常好,谢谢! –