2

I have a many-to-many relationship between Notes and Stacks. I am creating a form where a user can create a new note, with a title, body, and then a group of check boxes. The group of checkboxes are various Stacks. I want a user to be able to associate one or multiple Stacks with a particular note.

I am using the simple_form gem to do this. Everything is working except the Stacks will not save to the database. The title and body save, but not the Stacks. I have tested both sides of the relationship manually in the console, and they do yield the expected results -- it works.

One thing I notice when I watch what is going on in the Rails Server tab is Unpermitted parameters: stack_ids, as seen here:

Started POST "/notes" for 127.0.0.1 at 2014-10-06 16:00:21 -0600
Processing by NotesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"gMpbaYio0qkPLLrR6ICG0IJ7XNoy3Rn4RHLm3vwUU+I=", "note"=>{"title"=>"asdfs ", "body"=>"asdfasdf  asfsadf ", "stack_ids"=>["1", "2", ""]}, "commit"=>"Create Note"}
Unpermitted parameters: stack_ids

My notes_controller.rb has these params:

def notes_params
  params.require(:note).permit(:title, :body, :stack_id)
end

My stacks_controller.rb has these params:

def stacks_params
  params.require(:stack).permit(:title, :description, :note_id)
end

Here is the form:

<%= simple_form_for @note, :html => { :class => 'form-horizontal' } do |f| %> <%= f.input :title, placeholder: ":title", id: "note-form-title-field", class: "note-form-fields" %> <%= f.input :body, placeholder: ":body", id: "note-form-body-field", class: "note-form-fields" %> <%= f.association :stacks, as: :check_boxes %> <%= f.button :submit %> <% end %>

I have tried replacing :stack_id in the params with other variations, and always get the same result. Any ideas on how to get these Stacks to save to the database, associated with a note? Thanks.

HPJAJ
  • 1,464
  • 2
  • 13
  • 18

1 Answers1

1

This StackOverflow posting provides a detailed solution.

In summary, when declaring strong parameters, I needed to explicitly map the stack_ids key to an empty array in my notes_controller.rb file:

def notes_params params.require(:note).permit(:title, :body, stack_ids: []) end

Community
  • 1
  • 1
HPJAJ
  • 1,464
  • 2
  • 13
  • 18