【问题标题】:Can't save nested_attributes use chosen in rails无法保存在 rails 中选择的 nested_attributes 使用
【发布时间】: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


    【解决方案1】:

    在您的帖子#form 部分中,您应该将您的选择元素包装在fields_for 方法中:

    <%= f.fields_for :has_categories do |hc| %>
      <%= hc.select %>
      <%= hc.select :category_id, Category.all.map { |c| [c.name_category, c.id] },{}, { class: 'form-control', multiple: true } %>
    <%= end %>
    

    这将确保正确命名选择方法以传递嵌套属性。

    更多信息:http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for-label-Nested+Attributes+Examples

    【讨论】:

    • 现在我收到此错误Unpermitted parameter: has_categories 我还编辑了类似 params.require(:post).permit(...,:has_categories, post_has_categories_attributes: [ :post_id, :category_id ]) 的强参数我得到同样的错误
    猜你喜欢
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 2014-07-04
    相关资源
    最近更新 更多