0

I am trying to create a form with a list of checkboxes.

<%= form_for(@user, url: creators_path) do |f| %>
  <%= f.label :name %>
  <% Subject.all.each do |subject| %>
    <%= f.label subject.name %>
    <%= f.check_box :subject_ids, class: 'form-control' %>
  <% end %>
  <%= f.submit "Save changes", class: "btn btn-primary" %>
<% end %>

I want the resulting user_params to contain an array of the ids of chosen subjects.

With the above code, I get:

> params.require(:user)
  <ActionController::Parameters {"name"=>"John", "subject_ids"=>"0"} permitted: true>

But I want "subject_ids" to be an array:

> params.require(:user)
  <ActionController::Parameters {"name"=>"John", "subject_ids"=>[0,1,2,3]} permitted: true>

What is the correct way to handle collections in a Rails form?

1 Answer 1

1

You should be using strong params like this

def safe_params
  params.require(:user).permit(:name, subject_ids: [])
end

and in your actions

def create
  ..
  safe_params[:subject_ids] # will now be an array
  ..
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.