Reputation: 1485
I have a form for filtered search:
<%= form_tag admin_publications_path, method: "get", id: "filter", class: "filter" do %>
<%= label_tag "Category" %>
<%= select "publication", "category", options_for_select(options_for_categories, selected: params[:publication][:category]), {prompt: 'All'}, onchange: "$('#filter').submit();" %>
<% end %>
this works fine as long as there as params[:publication][:category] is available.
But if the params are not available, for instance when the view is rendered without previous search, I get the error:
undefined method `[]' for nil:NilClass
Is there a way to check from the view if the params are present?
thanks for your help,
Anthony
Upvotes: 1
Views: 2218
Reputation: 29599
Use fetch
. The second parameter will be the returned value when params[:publication]
is not present.
params.fetch(:publication, {})[:category]
Be warned though that the following will raise an exception
params = { publication: nil }
params.fetch(:publication, {})[:category] # NoMethodError nil.[]
Upvotes: 0
Reputation: 5931
Views should NOT know about params
.
In controller (or view helper) create variable like `
if params[:publication]
@selected = params[:publication][:category]
end
or even do it in 1 line
@selected = params[:publication].try(:[], :category)
Upvotes: 6