Choosing a Rails collection in a form that does not preserve the HABTM Association

In my Rails form, associations are not saved when I add the option to select multiple collections on the form. Why is this?

The form

<%= form_for @entry do |f| %>
  <% if @entry.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@entry.errors.count, "error") %> prohibited this entry from being saved:</h2>

      <ul>
      <% @entry.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>

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

  <div class="actions">
    <%= f.submit 'Submit' %>
  </div>
<% end %>

Strong parameters

private
    def entry_params
        params.require(:entry).permit(:content, :category_ids)
    end

Input model

class Entry < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :categories

  validates :content, :user_id, presence: true
end

Category Model

class Category < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :entries
end

Connection table

class EntriesCategories < ActiveRecord::Base
    belongs_to :entry
    belongs_to :categories
end
+4
source share
1 answer

Use this:

def entry_params
    params.require(:entry).permit(:content, :category_ids => [])
end

Due to multiple selection, you will get an array instead of a single value. So, specify category_idsas an array, allowing parameters

+5
source

Source: https://habr.com/ru/post/1535189/


All Articles