在我的Rails表单中,当我在表单中放置多个集合选择选项时,关联不会保存。这是为什么?
表格
<%= 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 %>
强参数
private
def entry_params
params.require(:entry).permit(:content, :category_ids)
end
条目模式
class Entry < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :categories
validates :content, :user_id, presence: true
end
类别模型
class Category < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :entries
end
加入表格
class EntriesCategories < ActiveRecord::Base
belongs_to :entry
belongs_to :categories
end
答案 0 :(得分:6)
使用此:
def entry_params
params.require(:entry).permit(:content, :category_ids => [])
end
由于多次选择,您将获得一个数组而不是一个值。因此,在允许参数
的同时将category_ids
指定为数组