Skip to main content

INSERT multiple records with accepts_nested_attributes_for

General • Asked by sacko idriss

Hi evry bady.
I have three models.
I want a form that gives the product list, just added the amount for inclusion in ventelinges.

class Produit < ActiveRecord::Base
  has_many :ventelignes
end```

```vente.rb
class Vente < ActiveRecord::Base
  has_many :ventelignes, dependent: :destroy
  has_many :produits, through: :ventelignes
  accepts_nested_attributes_for :ventelignes, allow_destroy: true
end```

```venteligne.rb
class Venteligne < ActiveRecord::Base
  belongs_to :vente
  belongs_to :produit
end```

Check out this episode! https://gorails.com/episodes/forum-nested-attributes-and-fields-for It covers how to do that with the form and params in order to properly set everything up.


I watched the episodes, but for me it's a bit special.

Started POST "/ventes" for 127.0.0.1 at 2016-03-08 13:07:26 +0000
Processing by VentesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"CBKOiGzB/XsulqthIZWDderNuxySxDwZVz+Lvk8QuaQwGaixW5P/35+C9SjqVGxxpD0HoFNZzMchAHowKiI1hg==", "vente"=>{"date_vente"=>"08-03-2016 13:06", "custom_id"=>"1", "ventelignes_attributes"=>{"0"=>{"produit_id"=>"1", "qte"=>"0"}, "1"=>{"produit_id"=>"2", "qte"=>"0"}, "2"=>{"produit_id"=>"3", "qte"=>"0"}, "3"=>{"produit_id"=>"4", "qte"=>"0"}, "4"=>{"produit_id"=>"5", "qte"=>"0"}, "5"=>{"produit_id"=>"6", "qte"=>"0"}, "6"=>{"produit_id"=>"7", "qte"=>"0"}}}, "button"=>""}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", -1000]]
(0.1ms) BEGIN
Venteligne Exists (0.4ms) SELECT 1 AS one FROM "ventelignes" WHERE ("ventelignes"."vente_id" IS NULL AND "ventelignes"."produit_id" = 1) LIMIT 1
Venteligne Exists (0.4ms) SELECT 1 AS one FROM "ventelignes" WHERE ("ventelignes"."vente_id" IS NULL AND "ventelignes"."produit_id" = 2) LIMIT 1
Venteligne Exists (0.3ms) SELECT 1 AS one FROM "ventelignes" WHERE ("ventelignes"."vente_id" IS NULL AND "ventelignes"."produit_id" = 3) LIMIT 1
Venteligne Exists (0.3ms) SELECT 1 AS one FROM "ventelignes" WHERE ("ventelignes"."vente_id" IS NULL AND "ventelignes"."produit_id" = 4) LIMIT 1
Venteligne Exists (0.2ms) SELECT 1 AS one FROM "ventelignes" WHERE ("ventelignes"."vente_id" IS NULL AND "ventelignes"."produit_id" = 5) LIMIT 1
Venteligne Exists (0.5ms) SELECT 1 AS one FROM "ventelignes" WHERE ("ventelignes"."vente_id" IS NULL AND "ventelignes"."produit_id" = 6) LIMIT 1
Venteligne Exists (0.3ms) SELECT 1 AS one FROM "ventelignes" WHERE ("ventelignes"."vente_id" IS NULL AND "ventelignes"."produit_id" = 7) LIMIT 1
(0.1ms) ROLLBACK
Redirected to http://0.0.0.0:3000/ventes/new
Completed 302 Found in 53ms (ActiveRecord: 3.0ms)


I can not seem to add to the database.


thank you in advance


Hi Sacko,

Mind posting your params method from the controller for Vente or what the params is actually is when its being pushed to the db


this is my vente controller

```class VentesController < ApplicationController
before_action :set_vente, only: [:show, :edit, :update, :destroy]

# GET /ventes
# GET /ventes.json
def index
@produits = Produit.order(id: :asc)

if params[:utf8]
  @ventes = Vente.date_between("#{params[:date1]}", "#{params[:date2]}")
else
  @ventes = Vente.recent
  @ventes = Vente.plivret if params[:plivret]
  @ventes = Vente.nlivret if params[:nlivret]
end
@crediteurs_customs = Vente.credit_customs_fideles if params[:credits]
#@crediteurs_clients_libre = Vente.credit_clients_libres if params[:credits]

end

# GET /ventes/1
# GET /ventes/1.json
def show

if @vente.custom_id != -1
  @cli = Custom.list.find(@vente.custom_id)
end

@ventelignes = @vente.ventelignes.select("categoriepro_id, produit_id,name,reference,qte,qtelivre,prix_u, remise,montant, ventelignes.id, ventelignes.etat").prod
@paiements_vente = @vente.paiements.list.jointure_vente.tout_paiement_pc.jointure_custom

@venteligne = Venteligne.new(:vente => @vente)

@paiement = Paiement.new(:vente => @vente, :custom => @cli)

end

# GET /ventes/new
def new
@vente = Vente.new
@produits = Produit.order(id: :asc)
# for p in @produits
# p.name
# @vente.ventelignes.build :produit_id => p.id, :name => p.name
# end

@produits.each { |int| @vente.ventelignes.build({ :produit_id => int.id, :name => int.name }) }

end

# GET /ventes/1/edit
def edit
end

# POST /ventes
# POST /ventes.json
def create
@vente = Vente.new(vente_params)

respond_to do |format|
  if @vente.save
    format.html { redirect_to @vente, notice: 'Vente was successfully created.' }
    format.json { render :show, status: :created, location: @vente }
  else
    format.html { redirect_to new_vente_path }
    format.json { render json: @vente.errors, status: :unprocessable_entity }
  end
end

end

# PATCH/PUT /ventes/1
# PATCH/PUT /ventes/1.json
def update
respond_to do |format|
if @vente.update(vente_params)
format.html { redirect_to @vente, notice: 'Vente was successfully updated.' }
format.json { render :show, status: :ok, location: @vente }
else
format.html { render :edit }
format.json { render json: @vente.errors, status: :unprocessable_entity }
end
end
end

# DELETE /ventes/1
# DELETE /ventes/1.json
def destroy
@vente.destroy
respond_to do |format|
format.html { redirect_to ventes_url, notice: 'Vente was successfully destroyed.' }
format.json { head :no_content }
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_vente
@vente = Vente.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def vente_params
  params.require(:vente).permit(
      :custom_id,
      :remise,
      :date_vente,
      :etat_vente,
      ventelignes_attributes: [
          :id,
          :produit_id,
          :qte,
          :remise,
          :_destroy
      ]
  )
end

end```


Jhon I am a beginner.


Hi Jhon
to understand the problems, watch this video please : https://www.youtube.com/watch?v=Aho_8omFInY&feature=youtu.be


I can not solve my problem. you do not want to help me.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.