Use of Nested Attributes with "has_many through" relationship table

Asked

Viewed 209 times

1

I have the following problem, I have a relationship:

class Servidor < ActiveRecord::Base
  has_many :lotacoes, :through=>:servidor_lotacoes
  has_many :servidor_lotacoes
end



class Lotacao < ActiveRecord::Base
  has_many :servidores,:through=>:servidor_lotacoes
  has_many :servidor_lotacoes
end


class ServidorLotacao < ActiveRecord::Base  
  belongs_to :lotacao
  belongs_to :servidor
end

Where ServidorLotacao has an extra attribute tipo:integer

How can I create a form (e.g. collection_select) to manage this relationship in Server, where you can still pass the type to be stored in the relationship table?

I thought about creating 3 multiples selects (one for each type) but getting this information on the other side is a bit complex.

More or less my code:

    <% ServidorLotacao.tipos.to_h.each_pair do |tipo_nome, tipo_codigo| %>
    <div class="field" >
      <%= f.label :lotacao_ids, tipo_nome %><br>

      <%= collection_select(:servidor, "lotacao_ids[#{tipo_codigo}]", 
        @lotacoes, 
        :id, :nome, {:selected => @servidor.lotacao_ids_for(tipo_codigo), :include_blank => true}, {:multiple => true, class: "select2_1",  style:"width: 100%;"}) %>
      </div>

    <% end %>

And the result in my controller

{"utf8"=>"✓",
 "_method"=>"patch",
 "authenticity_token"=>"r5KaLCrb1PR//q4HZ0p30dUeK1OHE7cjmtoken=",
 "servidor"=>
  {"nome"=>"123412312",
   "tipo"=>"1",
   "lotacao_ids"=>{"1"=>[""], "2"=>["", "87"], "3"=>[""]},
   "contatos_attributes"=>{"0"=>{"telefone"=>"(063) 8132-9584", "id"=>"605"}},
   "matricula"=>"56830",
   "cpf"=>"4539"},
 "action"=>"update",
 "controller"=>"servidores",
 "id"=>"340"}

Where lotacao_ids are the Ids of my stockings grouped by type. Any idea?

1 answer

1

That’s what you want?

# servidor_lotacao_controller.rb
def new
  @servidor_lotacao = ServidorLotacao.new
end

# new.html.erb
= form_for(@servidor_lotacao) do
  = f.label :servidor
  = f.collection_select (...)

  = f.label :lotacao
  = f.collection_select (...)

  = f.label :tipo
  = f.text_field :tipo

  = f.submit "Salvar"
end

If that’s not what you want, edit your question, because it’s not clear enough to me.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.