mardi 5 mai 2015

Many-to-many controller on rails 4

I'm trying to do a many-check-box with a many-to-many association. I have tree models Empresa:

class Empresa < ActiveRecord::Base
  has_many :empresa_pagamento
  has_many :formas_pagamentos, :through =>  :empresa_pagamento
  has_one :tipo_restaurante
  has_many :produtos
end

Forma Pagamento

class FormaPagamento < ActiveRecord::Base
  has_many :empresa_pagamento
  has_many :empresas, :through => :empresa_pagamento

end

Empresa Pagamento

class EmpresaPagamento < ActiveRecord::Base
  belongs_to :empresa
  belongs_to :forma_pagamento

end

On my empresa_controller I have my params

def empresa_params
       params.require(:empresa).permit(:nome, :descricao, :cnpj, :razao_social,:formas_pagamentos, :tipo_restaurante)
end

When i try to save i do :

def create
    @empresa = Empresa.new(empresa_params)    
    respond_to do |format|
      if @empresa.save
         @empresa.formas_pagamentos.each do |forma_pagamento|
          empresa_pagamento = EmpresaPagamento.new
          empresa_pagamento.forma_pagamento = FormaPagamento.find(forma_pagamento)
          empresa_pagamento.empresa = @empresa
          empresa_pagamento.save
        end      
        format.html { redirect_to @empresa, notice: 'Empresa was successfully created.' }
        format.json { render :show, status: :created, location: @empresa }
      else
        format.html { render :new }
        format.json { render json: @empresa.errors, status: :unprocessable_entity }
      end
    end
  end

on my _form i have

<div class="field">
    <%= f.label :formas_pagamentos %><br>
     <%= f.collection_select(:formas_pagamentos, FormaPagamento.all, :id, :nome,{:prompt => "Selecione"}, {:multiple => true}) %>

  </div>

Aucun commentaire:

Enregistrer un commentaire