简体   繁体   中英

Rails: What's a good way to deal with empty params array

In one of my views I have a form that will send data to the controller.

<%= form_for @user do |f| %>
  <%= f.error_messages %>

<% for committee in @committees %>
  <div>
    <%= check_box_tag "user[relevant_committee_ids][]", committee.id, @user.relevant_committees.include?(committee) %>
    <%= committee.name %>
  </div>

<% end %>
  <%= f.submit t(:save_settings) %>
<% end %>

If the form is empty, no params[:user] is generated which will lead the following code in my controller to fail:

@user.relevant_committee_ids = params[:user][:relevant_committee_ids] ||= [] 

With the error message:

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.[]

What's a nice, readable way to get an empty array if params[:user] is not generated?

Thanks in advance for any suggestions.

怎么样

@user.relevant_committee_ids = params[:user] ? params[:user][:relevant_committee_ids] : [] 

My try would be:

params[:user] ||= []
@user.relevant_committee_ids = params[:user][:relevant_committee_ids]
@user.relevant_committee_ids ||= []

Generally, I find it's readable enough to use x ||= [] syntax everywhere I must emphasize that I substitute empty collection for a nil value.

@user.relevant_committee_ids = params[:user].try(:[], :relevant_committee_ids) || []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM