1

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
4

1 に答える 1

0

質量の割り当ては正しいです。またはに渡しparams[:your_models_name]て、モデルを作成または更新します。強力なパラメーターは、大量に割り当てることができるパラメーターをホワイトリストに登録する方法です。YourModel.newYourModel.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パラメーターはボブの人物に割り当てられませんでした。

入力フィールドの形式に関する質問については、フォームに記載されている方法で入力する必要があります。これはあなたの場合ではありませんか?

于 2013-11-13T07:00:19.897 に答える