本文介绍了请为params(strong_parameters)使用新的推荐保护模型,或者在您的gemfile中添加`protected_attributes`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我向我的关系模型添加了一个attr_accessible时,发生了这种情况。

This happened when I added an attr_accessible to my Relationship model.

class Relationship < ActiveRecord::Base
  attr_accessible :followed_id
end

不使用Devise或protected_attributes gem,这是怎么回事?我知道在控制器中,你调用一个私有方法需要和允许的字段。这是你应该在模型中做的吗?这里的惯例是什么?

Without using Devise or a protected_attributes gem, what is the way around this? I know that in controllers you call a private method requiring and permitting fields. Is this something you should do in the model too? What is the convention here?

谢谢!

推荐答案

4您使用强参数而不是受保护的属性。 (您不需要将宝石包含在gemfile中,因为它已经包含在内)。

In Rails 4 you use Strong Parameters instead of Protected Attributes. (You don't need to include the gem in your gemfile as it's already included.)

您将Rails 3 attr_accessible代码从您的模型中取出,并将相应的代码放入你的控制器请参阅此处获取更多文档:

You take the Rails 3 attr_accessible code out of your model and put corresponding code into your controller. See here for more documentation: https://github.com/rails/strong_parameters

在你的情况下,类似于

class RelationshipController < ActionController::Base
  def create
    @relationship = Relationship.new(relationship_params)

    if @relationship.save
        # do something
    else
        # do something
    end
  end

  private
    def relationship_params
      params.require(:relationship).permit(:followed_id)
    end
end

编辑:

这是一个很好的文章,我刚刚遇到这个:

Here's a good article I just came across about this: http://blog.sensible.io/2013/08/17/strong-parameters-by-example.html

这篇关于请为params(strong_parameters)使用新的推荐保护模型,或者在您的gemfile中添加`protected_attributes`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 05:40