【问题标题】:accept data from checkboxes in nested_form and create records using the data from checkboxes接受来自nested_form 中复选框的数据并使用来自复选框的数据创建记录
【发布时间】:2014-10-07 15:22:15
【问题描述】:

我有一个产品类,产品对零个或多个角色可见。所以我创建了一个名为 content_roles 的多态模型,它存储角色的 id 和 content_id(将是 product_id 或 event_id)和 content_type(产品、事件等)。

我正在使用 nested_form gem 接受角色 id(使用 check_box)将产品和角色关系存储在 content_role 中

我面临的问题是我无法创建 content_role 记录。在我的日志中,我得到了未经许可的参数:role_id

参数:{"utf8"=>"✓", "authenticity_token"=>"xxxxxxxxxxxxxxxxxxxxdLH99ZWLrf8dgT3gcBops=", "product"=>{"product_name"=>"some product", "product_description"=>"some product description ", "content_roles_attributes"=>{"role_id"=>["1", "2", ""]}}, "commit"=>"创建产品"}

在我看来我已经写了

 = f.simple_fields_for :content_roles_attributes do |role|
  = role.input :role_id,label: "visible to", as: :check_boxes,label: "Role",collection: Role.all,:required=>true

控制器允许的参数看起来像

def product_params
 params.require(:product).permit(:product_description,:product_name,
 content_roles_attributes:  [:role_id,:id],
 multimedia_attributes:[:asset,:_destroy,:id])
end

产品型号看起来像

 class Product     
  has_many :content_roles, as: :content
  has_many :multimedia ,as: :storable
  # Nested attributes
  accepts_nested_attributes_for :multimedia
  accepts_nested_attributes_for :content_roles
 end

这就是 content_role 模型

class ContentRole < ActiveRecord::Base
 belongs_to :content, polymorphic: true
 belongs_to :role
 belongs_to :news
 belongs_to :product
end

【问题讨论】:

    标签: ruby-on-rails ruby nested-forms strong-parameters


    【解决方案1】:

    尝试将您的 product_params 更改为:

    def product_params
      params.require(:product).permit(
        :product_description,
        :product_name,
        content_roles_attributes:  [:id, role_id: []],
        multimedia_attributes: [:asset, :_destroy,:id]
      )
    end
    

    【讨论】:

    • 按照建议我尝试将 role_id 设置为数组,它给了我一个 TypeError(没有将字符串隐式转换为整数)。有什么建议可以解决吗??
    • @Adil - 这是另一个问题,您需要使用确切的错误消息以及回溯和相关代码(最有可能是控制器操作)来更新您当前的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    相关资源
    最近更新 更多