samedi 13 août 2016

Rails nested form with multiple check boxes - values not stored in the db

I really need a help here as I am running out of ideas what can be wrong here.

Models

class Rfq < ActiveRecord::Base
  belongs_to :purchase
  belongs_to :supplier
  belongs_to :customtemplate

  has_many :rfq_products
  accepts_nested_attributes_for :rfq_products, :allow_destroy => true
end

class RfqProduct < ActiveRecord::Base
  belongs_to :rfq 
end

Form

<%= simple_form_for @rfq do |f| %>
(...)
<%= f.simple_fields_for :rfq_products do |rfq_product|  %>
     <%= rfq_product.check_box :product, { :multiple => true }, 8, nil %>
     <%= rfq_product.check_box :product, { :multiple => true }, 9, nil %>
<% end %>
<%= f.button :submit %>
<% end %>

rfq_controller

def new
    @rfq = Rfq.new
    @rfq.rfq_products.build
end

def create
    @rfq = Rfq.new(rfq_params)

    respond_to do |format|
      if @rfq.save
        #format.html { redirect_to @rfq, notice: 'Rfq was successfully created.' }
        format.html { redirect_to :back, notice: 'Rfq was successfully created.' }
        format.json { render :show, status: :created, location: @rfq }
      else
        format.html { render :new }
        format.json { render json: @rfq.errors, status: :unprocessable_entity }
      end
    end
  end

def rfq_params
  params.require(:rfq).permit(:customtemplate_id, :supplier_id, :purchase_id, :code, 
      rfq_products_attributes: [ :id, :_destroy, product: [] ])
end

When I check params that I get after submitting form, I have sth like that:

pry(#<RfqsController>)> rfq_params
=> {"supplier_id"=>"7", "purchase_id"=>"4", "rfq_products_attributes"=>{"0"=>{"product"=>["8", "9"]}}}

and in the inserts that are genertaed, value of the products is omitted (they are not stored in the db). I do not get error that any value in the params is not permitted.

(3.1ms)  BEGIN
  SQL (1.1ms)  INSERT INTO "rfqs" ("supplier_id", "purchase_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["supplier_id", 7], ["purchase_id", 4], ["created_at", "2016-08-13 11:50:49.460475"], ["updated_at", "2016-08-13 11:50:49.460475"]]
  SQL (3.8ms)  INSERT INTO "rfq_products" ("rfq_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["rfq_id", 42], ["created_at", "2016-08-13 11:50:49.505250"], ["updated_at", "2016-08-13 11:50:49.505250"]]
   (39.0ms)  COMMIT

So what can cause that problem?




Aucun commentaire:

Enregistrer un commentaire