在 asp.net MVC 中,ActionDispatcher 会在一个动作中将参数转换为模型,这个过程称为模型绑定,在 Rails 中怎么称呼它? 轨道 3 中的质量分配,轨道 4 中的强参数?
如果我有一个包含许多输入字段的表单,格式为 100,000.00 的值,当我提交表单时,我需要保留所有值的格式,然后验证表单,如何在模型中格式化它用于保险目的?
更新:
# find all numeric attributes and define a write_attribute method
all_numeric_columns = Deal.columns.select {|x| [:float, :integer, :decimal].include?(x.type)}.map(&:name)
all_numeric_columns.each do |column|
class_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{column}=(the_value)
write_attribute(:#{column}, the_value.gsub(',', ''))
end
METHOD
end
质量分配是正确的。您可以通过将params[:your_models_name]
传递给YourModel.new
或YourModel.find(params[:id]).update_attributes params[:your_model]
来创建或更新模型。强参数是一种将可以批量分配的参数列入白名单的方法。
从指南:
class PeopleController < ActionController::Base
# Using "Person.create(params[:person])" would raise an
# ActiveModel::ForbiddenAttributes exception because it'd
# be using mass assignment without an explicit permit step.
# This is the recommended form:
def create
Person.create(person_params)
end
# This will pass with flying colors as long as there's a person key in the
# parameters, otherwise it'll raise an ActionController::MissingParameter
# exception, which will get caught by ActionController::Base and turned
# into a 400 Bad Request reply.
def update
redirect_to current_account.people.find(params[:id]).tap { |person|
person.update!(person_params)
}
end
private
# Using a private method to encapsulate the permissible parameters is
# just a good pattern since you'll be able to reuse the same permit
# list between create and update. Also, you can specialize this method
# with per-user checking of permissible attributes.
def person_params
params.require(:person).permit(:name, :age)
end
end
在上面的例子中,如果进来的参数看起来像这样:
{
person: {
name: 'bob',
age: 30,
admin: true
}
}
那么admin: true
参数就不会分配给鲍勃的人。
至于您的输入字段格式问题,它们应该在表单上出现。你不是这样吗?