![](/img/trans.png)
[英]ActiveModel::MassAssignmentSecurity::Error with nested attributes
[英]ActiveModel::MassAssignmentSecurity::Error even when using accepts_nested_attributes_for
我完整的错误消息是:
WorkoutsController#create中的ActiveModel :: MassAssignmentSecurity :: Error无法大规模分配受保护的属性:executive_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"}]}]}}
我的锻炼有很多锻炼条目,每个锻炼条目都可以包含很多条目详细信息。 该注释是可选的。
training.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
training_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
trainings_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
我尝试在exercise.rb中切换attr_accessible和accepts_nested_attributes_for的顺序,但是它不起作用。
我什至试图设定
config.active_record.whitelist_attributes = true
但是仍然无法创建。
accepts_nested_attributes_for
不会将任何属性添加到白名单。 无论您试图传递给update_attributes的任何键都必须列在attr_accessible中,在这种情况下,您需要向workout_entry
中添加attr_accessible
。
如果您使用fields_for,则它看起来确实存在表格错误,那么您应该使用可访问的键workout_entries_attributes
。
尝试在锻炼模型中可访问的attr中添加execution_entry_ids。
我决定在training和training_entry模型中不使用accepts_nested_attributes_for,因为它不适用于我。 我还更新了发送的json的格式。 详细信息在下面的链接中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.