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 t开发者_StackOverflowo get an empty array if params[:user] is not generated?
Thanks in advance for any suggestions.
How about
@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) || []
精彩评论