malcoauri
malcoauri

Reputation: 12199

Long strong params line breaking using Rubocop

There is the following code line:

  def tree_service_params
    params.permit(:id, { tree_service_categories_attributes: [:id, :title, :enabled, :_destroy, { tree_service_category_items_attributes: [:id, :image, :title, :description, :cost, :enabled] }] })
  end

This is simple Rails strong params. I need to break this line because it's too long. I use Rubocop to satisfy Ruby guidelines. How can I do it right? Thanks in advance!

Upvotes: 2

Views: 1162

Answers (3)

Siddhant
Siddhant

Reputation: 825

First solution(having different methods for different group of attributes) is more preferred if U have to take care of authorization as U will be able to authorize each methods independently in the first but not in the second.

def categories_attrs

// if authorized return params object , if not return null.

  { tree_service_categories_attributes: [:id, :title, :enabled, :_destroy, items_attrs] }

end

Upvotes: 0

Nick Veys
Nick Veys

Reputation: 23949

This can depend upon the other rules you have turned on in Rubocop. But it seems straight forward, just make the lines shorter. Here's one easy way:

def categories_attrs
  { tree_service_categories_attributes: [:id, :title, :enabled, :_destroy, items_attrs] }
end

def items_attrs
  { tree_service_category_items_attributes: [:id, :image, :title, :description, :cost, :enabled] }
end

def tree_service_params
  params.permit(:id, categories_attrs)
end

You could also go multi-line, like this:

def tree_service_params
  params.permit(:id, { 
    tree_service_categories_attributes: [
      :id, :title, :enabled, :_destroy, {
        tree_service_category_items_attributes: [
          :id, :image, :title, :description, :cost, :enabled
        ] 
      }
    ]
  })
end

Upvotes: 2

Arslan Ali
Arslan Ali

Reputation: 17812

One way is: You can break the code on multiple lines to make it more readable. But since, you are permitting a lot of attributes, that means there would be a lot of code in your controller, which is a bad thing per se. Controllers should always be skinny.

params.permit(:id, { 
  tree_service_categories_attributes: [ 
    :id, :title, :enabled, :_destroy, {
      tree_service_category_items_attributes: [
        :id, :image, :title, :description, :cost, :enabled
      ] 
    }
  ]
})

Upvotes: 0

Related Questions