2017-03-08 238 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?'條件 但的確,這個答案非常好,謝謝! –