Please use new recommended protection model for pa

2019-02-10 08:22发布

问题:

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