小编典典

在 Rails 4 中如何使用 attr_accessible?

all

attr_accessible似乎不再适用于我的模型。

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


阅读 67

收藏
2022-05-17

共1个答案

小编典典

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

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.

2022-05-17