Rails collection_select字段是重复条目

时间:2013-01-08 12:07:57

标签: ruby-on-rails forms select collections updates

在我的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

顺便说一句,更新是正确的:像我一样吗?

1 个答案:

答案 0 :(得分:0)

对于numImages更新(您的子问题),我建议在Component模型中使用before_update方法。

  before_update :set_numimages

  def set_numimages
    numImages = assets.size
  end

此外,您在@component上调用update_attributes,update_attribute 。这会调用三个保存操作。我建议你把它改成这个,看看问题是否仍然存在:

@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