【发布时间】:2016-11-14 22:34:02
【问题描述】:
我尝试使用选择和多对多关系构建一个表单,以存储帖子 > 类别,我遇到了一些麻烦
1.- 当我创建帖子时,我收到此消息 Unpermitted parameter: categories
2.- 帖子是商店,但类别不保存
这是我的代码 post.rb
class Post < ActiveRecord::Base
...
has_many :post_has_categories
has_many :categories, through: :post_has_categories
accepts_nested_attributes_for :post_has_categories,
reject_if: :all_blank,
allow_destroy: true
serialize :category_ids, Array
attr_accessor :categories
# Virtual attributes
def categories=(ids)
self.category_ids = ids.split(",").map(&:strip)
end
end
post_has_category.rb
class PostHasCategory < ActiveRecord::Base
belongs_to :post
belongs_to :category
accepts_nested_attributes_for :post
end
categories.rb
class Category < ActiveRecord::Base
...
has_many :post_has_categories
has_many :posts, through: :post_has_categories
end
我的部分posts#_form用这个调用数据
<%= f.select :categories, Category.all.map { |c| [c.name_category, c.id] },{}, { class: 'form-control', multiple: true } %>
我的 posts_controller 在 strong_parameters 我有这个
params.require(:post).permit(..., post_has_categories_attributes: [ :post_id, :category_ids ])
【问题讨论】:
标签: ruby-on-rails ruby nested-attributes jquery-chosen