Please use new recommended protection model for params(strong_parameters) or add `protected_attributes` to your gemfile

旧城冷巷雨未停 提交于 2019-12-30 05:03:41

问题


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

class Relationship < ActiveRecord::Base
  attr_accessible :followed_id
end

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?

Thanks!


回答1:


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.)

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

In your case, something like:

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

Edit:

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



来源:https://stackoverflow.com/questions/19130184/please-use-new-recommended-protection-model-for-paramsstrong-parameters-or-add

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!