请为 params(strong_parameters) 使用新的推荐保护模型或将 `protected_attributes` 添加到您的 gemfile [英] Please use new recommended protection model for params(strong_parameters) or add `protected_attributes` to your gemfile

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

问题描述

这发生在我将 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?

谢谢!

推荐答案

在 Rails 4 中,您使用强参数而不是受保护的属性.(你不需要在你的 gemfile 中包含 gem,因为它已经包含了.)

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 代码并将相应的代码放入控制器中.有关更多文档,请参阅此处:https://github.com/rails/strong_parameters

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

这是我刚刚看到的一篇很好的文章:http://blog.sensible.io/2013/08/17/strong-parameters-by-example.html

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) 使用新的推荐保护模型或将 `protected_attributes` 添加到您的 gemfile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆