首先我會名稱的根PARAM像「用戶」,那麼它給出的所有連接到控制器名稱和數據結構正在發送。
關於強參數。配置取決於你的Rails應用程序版本。 < = 3.x沒有包括這個,所以你需要添加gem。如果你是> = 4.x,那麼這已經是rails的一部分。
接下來在你的控制器中,你需要定義一個方法來過濾你需要的參數。我應該看起來像這樣:
class PeopleController < ApplicationController
def some_action
# Here you can call a service that receives people_params and takes
# care of the creation.
if PeopleService.new(people_params).perform
# some logic
else
# some logic
end
end
private
def base_people_params
params.permit(people: [:name, :date])
end
# Usually if you don't want to manipulate the params then call the method
# just #people_params
def people_params
base_people_params.merge(people: normalized_params)
end
# In case you decided to manipulate the params then create small methods
# that would that separately. This way you would be able to understand this
# logic when returning to this code in a couple of months.
def normalized_params
return [] unless params[:people]
params[:people].each_with_object([]) do |result, person|
result << {
name: normalize_name(person[:name]),
date: normalize_date(person[:date]),
}
end
end
def normalize_date(date)
Time.parse(date)
end
def normalize_name(name)
"#{name} - User"
end
end
如果您看到代碼開始進入自定義進入服務。這將有助於幫助您保持控制器精簡(和健康)。
當你在當時創建一個原因(而不是像這裏那樣的批處理)時,代碼更簡單一點,你使用散列而不是數組......但它幾乎是相同的。
編輯:
如果您不需要操縱特定PARAM那麼就不要
def normalized_params
return [] unless params[:people]
params[:people].each_with_object([]) do |result, person|
result << {
name: person[:name],
date: normalize_date(person[:date]),
}
end
end
THX了很多,但如果我不需要normalize_name名而錯過這一行,然後它從結果參數集中消失 –