class PeopleController < ApplicationController
def create
Person.create(person_params)
end
private
def person_params
params.require(:person).permit(:name, :age)
end
end
class Person
has_many :pets
accepts_nested_attributes_for :pets
end
class PeopleController < ApplicationController
def create
Person.create(person_params)
end
# ...
private
def person_params
params.require(:person).permit(:name, :age, pets_attributes: [:name, :category])
end
end
class NestedForm
include ActiveModel::MassAssignmentSecurity
attr_accessible :name,
:telephone, as: :create_params
def create_objects(params)
SomeModel.new(sanitized_params(params, :create_params))
end
end
# fix attr_accessible in an initializer
# wrap ActionController::Parameters code in singleton method defined
# from attr_accessible so controller code can call class method
# to get permitted parameter list
# e.g. model: class A < ActiveRecord::Base,
# controller calls A.permit_attr(params)
# lots simpler than moving all attr_accessible definitions to controllers
# bug: fails if more than one attr_accessible statement
def (ActiveRecord::Base).attr_accessible *fields
puts "attr_accessible:"+self.name+":permitted_params fields=#{fields.inspect}"
define_singleton_method("permit_attr") { |params|
# may have subclasses where attr_accessible is in superclass
# thus must require by subclass name so should calculate require at runtime
rq = self.name.downcase.to_sym
puts "...permit_attr:self=#{rq} permit(#{fields.inspect})"
params.require(rq).permit(fields)
}
end
为了防止多重attr_accessible声明,在定义方法之前,添加
raise "error: model can only have one attr_accessible declaration" if defined? permit_attr