Rails 4 中如何使用 attr_accessible?

2024-05-23

attr_accessible似乎不再在我的模型中工作。

Rails 4 中允许批量分配的方法是什么?


Rails 4 现在使用参数强 http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html.

保护属性现在是在控制器中完成的。这是一个例子:

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使用强参数,您需要指定哪些嵌套属性应列入白名单。

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 操作控制器指南中 http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters.

Note: 如果你还想用attr_accessible,你需要添加protected_attributes https://github.com/rails/protected_attributes给你的Gemfile。否则,你将面临RuntimeError.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails 4 中如何使用 attr_accessible? 的相关文章

随机推荐