首先我会名称的根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名而错过这一行,然后它从结果参数集中消失 –