2014-01-21 55 views
0

主要有以下几种型号:::加载ActiveModel为ForbiddenAttributesError多态关联

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 "Добавить" 

但 '创造' 的行动产生TimeDiscount.new行中的'ActiveModel :: ForbiddenAttributesError'。我使用Rails 4.我该如何解决它?谢谢。

+0

有什么安全参数? – emaillenin

+0

你是什么意思? – malcoauri

回答

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 "Добавить" 

给一个去。

+0

我使用has_one,而不是has_many关系。看看我的更新,并编辑你的答案。 – malcoauri

相关问题