ruby-on-rails – Rails集合选择表格不保存HABTM协会
发布时间:2020-12-17 03:06:47 所属栏目:百科 来源:网络整理
导读:在我的Rails表单中,当我在表单中放置多个集合选择选项时,关联不会保存.为什么是这样? 形成 %= form_for @entry do |f| % % if @entry.errors.any? % div id="error_explanation" h2%= pluralize(@entry.errors.count,"error") % prohibited this entry from
在我的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 解决方法
用这个:
def entry_params params.require(:entry).permit(:content,:category_ids => []) end 由于多次选择,您将获得一个数组而不是一个值.因此,在允许params的同时将category_ids指定为数组 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |