Question

This is a rails 3 app and it is confusing me. I have this:

class Coleta < ActiveRecord::Base
  has_many :coletas_produtos
  has_many :produtos, through: :coletas_produtos

  accepts_nested_attributes_for :produtos
end

class Produto < ActiveRecord::Base
  has_many :coletas
  has_many :coletas_produtos, through: :coletas
end

class ColetasProduto < ActiveRecord::Base
  belongs_to :produto
  belongs_to :coleta
end

When I try to save a new Coleta, I do it like this:

def create
  @coleta = Coleta.new(params[:coleta])

  respond_to do |format|
    if @coleta.save
      format.html { redirect_to(coletas_path, :notice => "Coleta cadastrada com sucesso.") }
    else
      format.html { render :action => "new" }
    end
  end
end

And this is my form:

<%= form_for(@coleta) do |f| %>
  <%= f.fields_for :produtos do |p| %>
    <div class="field left">
      <%= p.label :codigo, "Código" %><br />
      <%= p.text_field :codigo %>
    </div>
  <% end %>
<% end %>

This is working because it creates the correct records under the coletas_produtos table. My problem is that I want it to save ONLY the many-to-many relation, and not the produtos relation.

It keeps saving the records inside the produtos table along with the records on coletas_produtos. I want to ignore and keep only the latest records.

What is the best (is there a way?) way to do it?

Was it helpful?

Solution

Your has_many...through relationship definition needs some adjustment.

# app/models/produto.rb
class Produto < ActiveRecord::Base
  has_many :coletas_produtos
  has_many :coletas, through: :coletas_produtos
end

Please see "has_many :through" relation for proper definition.

Then in your ColetasController#new:

# app/controllers/coletas_controller.rb
def new
  @coleta = Coleta.new
  @coleta.coletas_produtos.build |cp| do 
    @produto = cp.build_produto
  end
end

This will instantiate a new instance of Coleta and build all the required relationships i.e. associated coletas_produtos and produto in your new action.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top