Toontje
Toontje

Reputation: 1485

how to check for existence params in view

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

Answers (3)

jvnill
jvnill

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

Filip Bartuzi
Filip Bartuzi

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

Marek Lipka
Marek Lipka

Reputation: 51151

You can do:

<% if params[:publication].present? %>

Upvotes: 3

Related Questions