use*_*029 4 ruby-on-rails ruby-on-rails-4
在我的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 %>
Run Code Online (Sandbox Code Playgroud)
强参数
private
def entry_params
params.require(:entry).permit(:content, :category_ids)
end
Run Code Online (Sandbox Code Playgroud)
进入模式
class Entry < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :categories
validates :content, :user_id, presence: true
end
Run Code Online (Sandbox Code Playgroud)
分类模型
class Category < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :entries
end
Run Code Online (Sandbox Code Playgroud)
加入表格
class EntriesCategories < ActiveRecord::Base
belongs_to :entry
belongs_to :categories
end
Run Code Online (Sandbox Code Playgroud)
用这个:
def entry_params
params.require(:entry).permit(:content, :category_ids => [])
end
Run Code Online (Sandbox Code Playgroud)
由于多次选择,您将获得一个数组而不是一个值.因此,category_ids在允许参数时指定为数组
| 归档时间: |
|
| 查看次数: |
2864 次 |
| 最近记录: |