2014-01-21 92 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

相關問題