私の 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 を更新するのは正しいですか?