Mika Vatanen
Mika Vatanen

Reputation: 4027

How to simplify this nested param include check?

In rails, I've got this checkbox tag, where the checked value should be true if an element is included in post array.

- checked = (params[:comments] && params[:comments][:pictures] && params[:comments][:pictures].include?(comment.id))
=check_box_tag "comments[pictures][]", comment.id, checked

The checked part looks very ugly. How to catch the error if params[:comments] or params[:comments][:pictures] is not set? I tried

- checked = (params[:comments][:pictures].include?(comment.id)) || false

But it does not work.

Upvotes: 2

Views: 291

Answers (2)

Pavling
Pavling

Reputation: 3963

You could merge in a hash of default values, and then you are sure there's a params[:comments][:pictures] value (an empty array in this instance):

params = {:comments => {:pictures => []}}.merge(params)
checked = params[:comments][:pictures].include?(comment.id)

Upvotes: 0

ka8725
ka8725

Reputation: 2918

I would recommend you to install simple_form and use:

= simple_form_for @comment do |f|
  = f.association :pictures, :as => 'boolean'

Upvotes: 3

Related Questions