mrvncaragay
mrvncaragay

Reputation: 1260

Rails: Strong parameters, Does it have to be present all the time?

As the title says. I know that strong parameters is to prevent other unauthorized attributes to be included when updating or creating new objects. I've seen codes that doesn't have strong parameters. For example in Hartl's tutorial relationships controller:

class RelationshipsController < ApplicationController
  before_action :logged_in_user

  def create
    @user = User.find(params[:followed_id])
    current_user.follow(@user)
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end
  end

  def destroy
    @user = Relationship.find(params[:id]).followed
    current_user.unfollow(@user)
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end
  end
end  

and others have it included such as creating new post or user etc. so my question is, when is the practice to use strong parameters?

Upvotes: 1

Views: 128

Answers (3)

nikkypx
nikkypx

Reputation: 2005

Yes, not using strong parameters will raise ActiveModel::ForbiddenAttributesError so it's not optional unless you manage to override this behavior.

In the above example he is just retrieving a record and then creating a relationship with that id in the model.

def follow!(other_user)
  relationships.create!(followed_id: other_user.id)
end

Upvotes: 1

Ilija Eftimov
Ilija Eftimov

Reputation: 820

I would say - use strong params for any actions where you use mass-assignment. This means that, actions like create or update must employ strong params.

For example, instead of having:

@object.update_attributes(params[:object])

Just have a:

@object.update_attributes(object_params)

Which will whitelist params for you. Also, it allows you to pass-through different params for different actions, with methods like object_update_params and object_create_params which will whitelist params for update and params for create, respectively.

Upvotes: 1

Kumar
Kumar

Reputation: 3126

Its ideal to use strong parameters when mass assigning values. Like creating new post or user. It may allows attackers to set any database column’s value.

Check out Rails official guide for it.

Doing like these is fine, as long as you know and mentioning model attributes.

@user = User.find(params[:followed_id])
@user = Relationship.find(params[:id]).followed

Upvotes: 2

Related Questions