Use of Nested Attributes with relationship table "has_many through"

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 (ex collection_select ) to manage this relationship in Server, where I can still pass the type to be stored in the relationship table?

I thought about creating 3 multiple selections (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 ideas?

    
asked by anonymous 23.05.2014 / 23:03

1 answer

1

Would that be 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 this is not what you want, edit your question because it is not clear enough for me.

    
27.05.2014 / 03:13