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

Но 'создать' действие порождает 'ActiveModel :: ForbiddenAttributesError' в строке TimeDiscount.new. Я использую 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

Смежные вопросы