使用 Rubocop 的长强参数断线

Long strong params line breaking using Rubocop

有如下代码行:

  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

这是简单的 Rails 强大的参数。我需要打破这条线,因为它太长了。我使用 Rubocop 来满足 Ruby 准则。我怎样才能做对?提前致谢!

一种方法是:您可以将代码分成多行以使其更具可读性。但是,由于您允许使用很多属性,这意味着您的控制器中会有很多代码,这本身就是一件坏事。控制器应该总是瘦的。

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

这可能取决于您在 Rubocop 中启用的其他规则。但它看起来很直接,只是让线条更短。这是一种简单的方法:

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

你也可以多行,像这样:

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

如果您必须处理授权,则第一种解决方案(对不同的属性组使用不同的方法)更可取,因为您将能够在第一个中独立地授权每个方法,但在第二个中不能。

def categories_attrs

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

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

end