ActiveModel :: ForbiddenAttributesError用于多态关联

时间:2014-01-21 06:56:47

标签: ruby-on-rails

有以下型号:

class Discount < ActiveRecord::Base
    belongs_to :content, polymorphic: true

    validates :value, presence: true
end 

class TimeDiscount < ActiveRecord::Base
    has_one :discount, as: :content, dependent: :destroy

    validates :start_time, :end_time, presence: true

    accepts_nested_attributes_for :discount
end

以下控制器:

class Admin::TimeDiscountsController < ApplicationController
    def new
        @time_discount = TimeDiscount.new
    end

    def create
        @time_discount = TimeDiscount.new(time_discount_params)
        if @time_discount.save
            redirect_to root_path
        else
            render 'new'
        end
    end

    private
        def time_discount_params
            params.require(:time_discount).permit.tap do |whitelisted|
                whitelisted[:start_time] = params[:time_discount][:start_time]
                whitelisted[:end_time] = params[:time_discount][:end_time]
                whitelisted[:discount_attributes] = params[:time_discount][:content]
            end
        end
end

形式:

  = form_for @time_discount, url: admin_time_discounts_path do |f|
    .row
      = f.label :start_time
      = f.text_field :start_time
    .row
      = f.label :end_time
      = f.text_field :end_time
    = f.fields_for :content do |discount|
      .row
        = discount.label :value
        = discount.text_field :value
    .row 
      = f.submit "Добавить"

但是'create'动作在TimeDiscount.new行中生成'ActiveModel :: ForbiddenAttributesError'。我使用Rails 4.我该如何解决?谢谢。

1 个答案:

答案 0 :(得分:0)

def time_discount_params
  params.require(:time_discount).permit(:start_time, :end_time, content: [:id, :start_time, :end_time])
end

这可能是您想要的,而不是您在上面定义的方法。这是假设您通过以下方式创建它:

= form_for @time_discount, url: admin_time_discounts_path do |f|
.row
  = f.label :start_time
  = f.text_field :start_time
.row
  = f.label :end_time
  = f.text_field :end_time
= f.fields_for :content, @time_discount.content.build do |discount|
  .row
    = discount.label :value
    = discount.text_field :value
.row 
  = f.submit "Добавить"

放手一搏。