0

私の Rails アプリ フォームには、複数選択用の次のコードがあります。

<div class="field">
  <%= f.label :frameworks %><br />
  <%= f.collection_select :framework_ids, Framework.all, :id, :name, {}, {:multiple => true}  %>
</div>

作成時に問題なく動作し、編集ビューで以前に選択したフレームワークを正しく表示します。

しかし、他の更新されたフィールドを送信すると、データベース内のフレームワーク エントリが繰り返されます。

たとえば、「framework1」、「frameworks2」を選択した場合、データベース「framework1」、「frameworks2」、「framework1」、「frameworks2」を更新した後、もう一度「framework1」を更新すると、 「frameworks2」、「framework1」、「frameworks2」、「framework1」、「frameworks2」。

では、それを防ぐにはどうすればよいのでしょうか。

編集: コントローラはここにあります:

@component = Component.find(params[:id])

    respond_to do |format|
        if @component.update_attributes(params[:component])
          @component.update_attribute(:numImages, @component.assets.size)
          @component.save

          format.html { redirect_to @component, notice: 'Component was successfully updated.' }
          format.json { head :no_content }
        else
          format.html { render action: "edit" }
          format.json { render json: @component.errors, status: :unprocessable_entity }
        end
    end

終わり

ところで、私のように :numImages を更新するのは正しいですか?

4

1 に答える 1

0

numImages の更新 (サブ質問) については、Component モデルで before_update メソッドを使用することをお勧めします。

  before_update :set_numimages

  def set_numimages
    numImages = assets.size
  end

また、update_attributes、update_attributeを呼び出して、@component に保存します。これにより、3 つの保存アクションが呼び出されます。これに変更して、問題が解決しないかどうかを確認することをお勧めします。

@component = Component.find(params[:id])  

respond_to do |format|
  if @component.update_attributes(params[:component])
    format.html { redirect_to @component, notice: 'Component was successfully updated.' }
    format.json { head :no_content }
  else
    format.html { render action: "edit" }
    format.json { render json: @component.errors, status: :unprocessable_entity }
  end
end
于 2013-01-08T12:52:56.533 に答える