【问题标题】:Rails collection_select field is repeating entriesRails collection_select 字段重复条目
【发布时间】:2013-01-08 12:07:57
【问题描述】:

在我的 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”中,如果我再更新一次:“框架1”、“框架2”、“框架1”、“框架2”、“框架1”、“框架2”。

那么我应该怎么做才能防止它呢?

编辑: 控制器在这里:

@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 是否正确?

【问题讨论】:

  • 请提供您的控制器端代码,问题存在而不是在视图页面上
  • 我已经添加了控制器部分。

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


【解决方案1】:

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

  before_update :set_numimages

  def set_numimages
    numImages = assets.size
  end

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

@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    相关资源
    最近更新 更多