ActiveModel :: MassAssignmentSecurity ::即使使用accepts_nested_attributes_for也会出错

时间:2013-02-21 06:05:40

标签: ruby-on-rails ruby-on-rails-3

我的完整错误信息是:

  

ActiveModel :: MassAssignmentSecurity ::错误   WorkoutsController #crein无法批量分配受保护的属性:   workout_entry

我发送的参数如下:

{"workout"=>{"unit"=>"kg", "name"=>"2013-02-20T21:26:19", "note"=>nil, "workout_entry"=> [{"workout_entry_number"=>"1", "exercise_id"=>2, "entry_detail"=>[{"set_number"=>"1", "weight"=>"32", "reps"=>"43"}]}]}}

我有一个锻炼,有很多锻炼条目,每个锻炼条目可以有很多条目细节。该笔记是可选的。

workout.rb

class Workout < ActiveRecord::Base
    has_many :workout_entries, dependent: :destroy

    attr_accessible :id, :name, :note, :unit, :workout_entries_attributes
    belongs_to :user
    accepts_nested_attributes_for :workout_entries

    validates_presence_of :name
    validates_presence_of :unit, :inclusion => %w(kg lb)
    validates_associated :workout_entries

    default_scope order("created_at DESC")

end

workout_entry.rb

class WorkoutEntry < ActiveRecord::Base

    belongs_to :workout
    belongs_to :exercise
    has_many :entry_details, dependent: :destroy

    attr_accessible :workout_id, :exercise_id, :workout_entry_number, :entry_details_attributes
    accepts_nested_attributes_for :entry_details

    validates :exercise_id, presence: true, numericality: {only_integer: true}, :inclusion => { :in => 1..790 }
    validates :workout_id, presence: true, numericality: {only_integer: true, greater_than_or_equal_to: 1}
    validates :workout_entry_number, presence: true, numericality: {only_integer: true, greater_than_or_equal_to: 1}

end

workouts_controller.rb

class WorkoutsController < ApplicationController
    respond_to :json
    before_filter :authenticate_user!

    def index
        respond_with(current_user.workouts)
    end

    def show
        respond_with(current_user.workouts.find(params[:id]))
    end

    def create
        respond_with(current_user.workouts.create(params[:workout]))
    end

    def update
        @workout = current_user.workouts.find(params[:id])
        if @workout.update_attributes(params[:workout])
          render json: @workout, status: :ok
        else
          render json: @workout.errors, status: :unprocessable_entity
        end
    end

    def destroy
        respond_with(current_user.workouts.destroy(params[:id]))
    end

end

我尝试在workout.rb中切换attr_accessible和accepts_nested_attributes_for的顺序,但它不起作用。

我甚至试图设置

config.active_record.whitelist_attributes = true

但仍然阻止了创作。

3 个答案:

答案 0 :(得分:0)

accepts_nested_attributes_for不会向白名单添加任何属性。无论您尝试传递给update_attributes的密钥必须在attr_accessible中列出,在您的情况下,您需要将workout_entry添加到attr_accessible

如果您使用fields_for,那么它看起来似乎表单中有错误,那么它应该使用您可以访问的密钥workout_entries_attributes

答案 1 :(得分:0)

尝试在锻炼模型中可访问的attr中添加workout_entry_ids。

答案 2 :(得分:0)

我决定不在workout和workout_entry模型中使用accepts_nested_attributes_for,因为它不适合我。我还更新了发送的json的格式。详情请见以下链接

link