如何在铁轨中保护你的参数?

时间:2013-11-13 06:40:12

标签: ruby-on-rails validation

在asp.net mvc中,actiondispatcher会将params变成一个动作中的模型,这个过程称为模型绑定,你如何在rails中调用它?轨道3中的质量分配,轨道中的强参数4?

如果我有一个包含许多输入字段的表单,这些值形成为100,000.00,当我提交表单时,我需要保留格式化所有值然后验证表单,如何在模型中格式化以用于保险目的?< / p>

更新:

 # 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

1 个答案:

答案 0 :(得分:0)

质量分配是正确的。您可以通过将params[:your_models_name]传递给YourModel.newYourModel.find(params[:id]).update_attributes params[:your_model]来创建或更新模型。强参数是将可以批量分配的参数列入白名单的方法。

From the guides:

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 param不会被分配给bob的Person。

至于你的输入字段格式问题,它们应该出现在表格中。这不是你的情况吗?