Association is duplicated on form error

时间:2016-02-12 20:54:16

标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-4.2

I need to save the same association twice, so I have this in my controller:

    'click .addField':function(event){
        console.log($(event.currentTarget).closest('.imgRef').value);
    }

And I have this in my form:

def new
  @negocio = Negocio.new
  @setores = Setor.all.collect { |s| [s.nome, s.id] }
  2.times { @negocio.negocios_setores.build }
end

def create
  @negocio = Negocio.new(negocios_params)
  respond_to do |format|
    if @negocio.save
      format.html { redirect_to negocio_path(@negocio) }
    else
      format.html {
        flash.now[:alert] = I18n.t("negocios.erro")
        render action: :new
      }
    end
  end
end

def edit
  @negocio = Negocio.find(params[:id])
  @setores = Setor.all.collect { |s| [s.nome, s.id] }
end

def update
  @negocio = Negocio.find(params[:id])
  respond_to do |format|
    if @negocio.update(negocios_params)
      format.html { redirect_to negocio_path(@negocio), notice: I18n.t("negocios.atualizado") }
    else
      format.html {
        flash.now[:alert] = I18n.t("negocios.erro")
        render :edit
      }
    end
  end
end

And my model has:

= f.simple_fields_for :negocios_setores, wrapper: false do |s|
  .col-md-6
    = s.input :setor_id, collection: @setores, input_html: { class: "chosen-select" }

The thing is, it works fine when I'm creating the object. If the error is thrown, it doesn't duplicate the association. When I try to update the object, the page throws an error and I end up with 4 select boxes.

Can someone please help me understand this?

0 个答案:

没有答案