0

I have a Ruby on Rails application with some generated scaffold. Now, in one of them I need to add a parameter that wasn't planned initially.

The situation is that I have two objects: Block and Keywords. The relationship between them is has_and_belongs_to_many. That allows me to have many keywords associated to many blocks and vice versa. I want to add the option to add some keywords to the object Block during the creation.

I added the following code in the /views/blocks/_form.html.erb file:

  <div class="field">
    <%= f.label :keywords %><br>
    <%= f.collection_select(:keywords, @keywords.order(:name), :id, :name, {include_blank: true}, {:multiple => true}) %>
  </div>

I added the parameter in the controller as well:

def block_params
  params.require(:block).permit(:name, :title, :description, :price, :instagram, :image, :main, :action, :keywords, :block_type_id, :module_keyword_id, :playlist_id)
end

Nevertheless I get this message in the log

Unpermitted parameter: keywords

and the keywords are not added to the block. What am I missing?

ste
  • 3,087
  • 5
  • 38
  • 73

1 Answers1

0

When a parameter is an array, you have to permit it as an array with this:

def block_params
  params.require(:block).permit(:name, :title, :description, :price, :instagram, :image, :main, :action, :block_type_id, :module_keyword_id, :playlist_id, :keywords, keywords: [])
end

note the "keywords: []", also note that I also left the ":keywords" key, that permits the param when you send an empty value too (en case you are removing all keywords for example).

arieljuod
  • 15,460
  • 2
  • 25
  • 36
  • Hello there! with your code I get this error: .../blocks_controller.rb:92: syntax error, unexpected ',', expecting => ..., keywords: [], :block_type_id, :module_keyword_id, :playlis... ... ^ – ste Sep 26 '16 at 10:43
  • My bad, you have to put the "keywords: []" at the end, I'll edit my answer. – arieljuod Sep 27 '16 at 15:05