0

複数のレコードを保存しているフォームを送信しています。パラメーターは次のようになります。

{
  "utf8"=>"✓",
  "_method"=>"put",
  "products"=> {
    "321" => {
        "sale_price"=>"10"
    },
    "104" => {
        "sale_price"=>"10"
    }
  }
}

それから私のコントローラーには、これがあります:

@updated_products = Product.update(params[:products].keys, params[:products].values)

これは、キー(321、104)がIDであると想定しています。
ただし、to_paramモデルでを使用して、URLをIDから別の列の値に変更しています。

ステートメントparams[:products].keysでIDを使用できるように、を取得して適切なIDと交換する方法はありますか。方法がわかりませんが、IDを取得するために.update()使用できます。Product.find_by_column_name(321).idRailsはまだ新しいです。

どんな助けでもいただければ幸いです。ありがとう。

4

1 に答える 1

1

ここ でソースコードを見ると、#update各キーを繰り返し実行して実行update_attributesされるため、すべての検証が実行されます。メソッドを次のように変更できます

@updated_products = params[:products].inject([]) do |array, (column_id, attributes)|
  product = Product.find_by_column_id column_id
  if product.update_attributes(attributes)
    array << product
  else
    array
  end
end

これは少し複雑に見えるかもしれませんが、以下のこれと同じで、理解しやすく、コードを読むのが簡単です。

@updated_products = []

params[:products].each do |column_id, attributes|
  product = Product.find_by_column_id column_id
  if product.update_attributes(attributes)
    @updated_products << product
  end
end
于 2013-02-18T00:50:57.797 に答える