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

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。

其他回答

Rails 5的更新:

gem 'protected_attributes' 

似乎已经不管用了。但给:

宝石的protected_attributes_continued

一试。

1)通过在应用程序的Gemfile中添加这一行来更新设计,以便它可以处理Rails 4.0:

gem 'devise', '3.0.0.rc' 

然后执行:

$ bundle

2)在rails 4.0中再次添加attr_accessible的旧功能

尝试使用attr_accessible,不要注释掉它。

将这一行添加到应用程序的Gemfile中:

gem 'protected_attributes'

然后执行:

$ bundle

我们可以用

params.require(:person).permit(:name, :age)

在person是Model的地方,你可以在方法person_params上传递这段代码,并在create方法或else方法中使用params[:person]

如果你更喜欢attr_accessible,你也可以在Rails 4中使用它。 你应该像gem一样安装它:

gem 'protected_attributes'

之后,你可以像在Rails 3中那样在你的模型中使用attr_accessible

而且,我认为这是最好的方法-使用表单对象来处理大量赋值,并保存嵌套对象,你也可以使用protected_attributes gem那种方式

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

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。