Long strong params line breaking using Rubocop

1.1k views Asked by At

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!

3

There are 3 answers

0
Nick Veys On BEST ANSWER

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
0
Siddhant On

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
0
Arslan Ali On

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
      ] 
    }
  ]
})