attr_accessible似乎不再适用于我的模型。
attr_accessible
在 Rails 4 中允许批量分配的方法是什么?
Rails 4 现在使用强参数。
保护属性现在在控制器中完成。这是一个例子:
class PeopleController < ApplicationController def create Person.create(person_params) end private def person_params params.require(:person).permit(:name, :age) end end
不再需要attr_accessible在模型中设置。
accepts_nested_attributes_for
为了使用accepts_nested_attribute_for强参数,您需要指定应将哪些嵌套属性列入白名单。
accepts_nested_attribute_for
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
关键字是不言自明的,但以防万一,您可以在 Rails Action Controller 指南中找到有关强参数的更多信息。
注意 :如果你还想使用attr_accessible,你需要添加protected_attributes到你的Gemfile. 否则,您将面临RuntimeError.
protected_attributes
Gemfile
RuntimeError