Rails:如何使强参数易于阅读

时间:2016-06-15 13:18:08

标签: ruby-on-rails ruby-on-rails-4

我的应用程序具有如下强大的参数。

如何让这段代码易于阅读?

这一行有很多attributes

我的控制器

  def create
    @schedule = current_user.schedules.build(schedule_params)
    ...
  end

  ...

  def schedule_params
    params.require(:schedule).permit(:title, :departure_date, rooms_attributes: [:id, :_destroy, :room, :room_address, :day, :ccy, :amount, events_attributes: [:id, :_destroy, :start_at, :end_at, :title, :detail, :category, :ccy, :amount, amounts_attributes: [:id, :_destroy, :ccy, :amount]]])
  end

如果你能给我任何建议,我将不胜感激。

5 个答案:

答案 0 :(得分:3)

除了字符串外,红宝石大多忽略了空白区域。这使得可以轻松地将一行代码分成多个部分。您可以利用它来使参数更易于阅读:

def schedule_params
  params.require(:schedule).permit(
    :title, :departure_date,
    rooms_attributes: [
      :id, :_destroy, :room, :room_address, :day, :ccy, :amount,
      events_attributes: [
        :id, :_destroy, :start_at, :end_at, 
        :title, :detail, :category, :ccy, :amount, 
        amounts_attributes: [:id, :_destroy, :ccy, :amount]
      ]
    ])
end

答案 1 :(得分:1)

一种选择是单独定义嵌套数组,例如

def schedule_params
  amount_attributess = [:id, :_destroy, :ccy, :amount]
  event_attributes = [:id, :_destroy, :start_at, :end_at, :title, :detail, :category, :ccy, :amount, amounts_attributes: amount_attributess]
  room_attributes = [:id, :_destroy, :room, :room_address, :day, :ccy, :amount, events_attributes: event_attributes]
  params.require(:schedule).permit(:title, :departure_date, rooms_attributes: room_attributes)
end

答案 2 :(得分:1)

您可以添加一些缩进,它可以提高易读性并减少代码中出现错误的可能性,这绝对是最佳做法!

你也可以按照这样的编码风格指南:

def schedule_params
  params.require(:schedule).permit(
    :title,
    :departure_date,
    rooms_attributes: [
      :id,
      :_destroy,
      :room,
      :room_address,
      :day,
      :ccy,
      :amount,
      events_attributes: [
        :id,
        :_destroy,
        :start_at,
        :end_at,
        :title,
        :detail,
        :category,
        :ccy,
        :amount,
        amounts_attributes: [
          :id,
          :_destroy,
          :ccy,
          :amount
        ]
      ]
    ]
  )
end

答案 3 :(得分:0)

def schedule_params
  params.require(:schedule).permit!
end

看起来容易阅读?是。

安全的?否。

答案 4 :(得分:0)

易。

使用params数组在模型中保持常量。这样你就不必在控制器中重新输入它们

class User < ActiveRecord::Base
  PARAMS = [:name, :email, :password]
end

然后在控制器中

def user_params
  params.require(:user).permit(User::PARAMS)
end

如果它们是嵌套的,您甚至可以在控制器中将多个模型组合在一起