我想實現一個簡單的搜索和排序爲我的webapp。我正在關注railscast和這個railscast。Rails無法將未經許可的參數轉換爲散列
我爲此我使用的鏈接排序功能應用助手是:
def sortable(column, title = nil)
title ||= column.titleize
css_class = column == sort_column ? "current #{sort_direction}" : nil
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, params.merge(:sort => column, :direction => direction, :page => nil), {:class => css_class}
end
我在視圖中使用這些。在控制器中,我使用白名單爲:用於消毒
@listingssearch.where(:vehicletype => 'Car').order(sort_column + " " + sort_direction).paginate(:page => params[:page], :per_page => 30)
私有方法:
private
def sort_column
Listing.column_names.include?(params) ? params[:sort] : "rateperhour"
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
end
我試着用在私有方法合併:
(Listing.column_names + params) but its not working
對於輔助方法當我嘗試向排序鏈接提供搜索參數時出現錯誤:無法將未允許的參數轉換爲散列
它顯示的錯誤是合併
link_to title, params.merge(:sort => column, :direction => direction, :page => nil), {:class => css_class}
周圍的otherway正常工作:
<%= bootstrap_form_for listings_path, :method => 'get' do %>
<%= hidden_field_tag :direction, :value => params[:direction] %>
<%= hidden_field_tag :sort,:value => params[:sort] %>
<div class= "col-sm-12 col-lg-12 col-md-12" style = "margin: auto;">
<h6 style = "color:#7C064D;"><strong> PICK A DATE <span class="glyphicon glyphicon-calendar"></span></strong>
<%= date_field_tag :startdate, params[:startdate], placeholder: 'DATE' %>
</h6>
</div>
<div class= "col-sm-12 col-lg-12 col-md-12" style = "margin: auto;">
<p>
<%= text_field_tag :near, params[:near], placeholder: ' Destination' %>
<%= text_field_tag :radius, params[:radius], placeholder: ' Search Radius' %>
</p>
</div>
<div class= "col-sm-12 col-lg-12 col-md-12" style = "margin: auto;">
<p>
<%= text_field_tag :min, params[:min], placeholder: ' Minimum Rate Per Hour' %>
<%= text_field_tag :max, params[:max], placeholder: ' Maximum Rate Per Hour' %>
</p>
</div>
<div class= "col-sm-12 col-lg-12 col-md-12" style = "margin-top: 10px;">
<%= submit_tag "Search", class: "btn btn-info", style: "width: 40%; background-color: #E20049; border: #e20049;" %>
<%= link_to 'View All', root_path, class: "btn btn-info", style: "width: 40%; background-color: #E20049; border: #e20049;" %>
</div>
<!-- <div class= "col-sm-6 col-lg-6 col-md-6" style = "margin-top: 10px;">
</div> -->
<% end %>
我的問題是如何堅持搜索PARAMS在導軌5排序輔助方法?我做錯了什麼?
您是否在資源許可方法本身傳遞搜索和排序參數? –
@SauravPrakash我擴展了一些答案,以包含一些示例,並對導致該異常的內容進行了輕微更正。這是否解決您的問題? – Max
謝謝!明確傳遞參數將有助於防止sql注入。這將是繼續而不是request.params的正確方法。雖然兩者都有效。 –