1
votes

I have a nested form which is refusing to insert a new record into the DB, despite the parent inserting fine. Undoubtedly an obvious one, but can someone advise why?

Parent model:

class Delivery < ActiveRecord::Base
  attr_accessible :orders_attributes
  has_many :orders, as: :orderable
  accepts_nested_attributes_for :orders

Nested model

class Order < ActiveRecord::Base
  attr_accessible :info
  belongs_to :orderable, polymorphic: true
  belongs_to :delivery

Parent controller

  def new
    @delivery = Delivery.new
    order = @delivery.orders.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @delivery }
    end
  end

Form

= form_for @delivery do |f|

  = fields_for :orders do |builder|
    = builder.label :info
    = builder.text_area :info
  .actions
    = f.submit

Output:

Started POST "/deliveries" for 127.0.0.1 at 2013-02-13 16:06:53 +0100 Processing by DeliveriesController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"MdNjphnBQaaHdxelT7RnWDNG2XPpDTQipDKAOkT57h0=", "orders"=>{"info"=>"1222"}, "commit"=>"Create Delivery"} (0.1ms) begin transaction SQL (2.7ms) INSERT INTO "deliveries" ("created_at", "updated_at") VALUES (?, ?) [["created_at", Wed, 13 Feb 2013 15:06:53 UTC +00:00], ["updated_at", Wed, 13 Feb 2013 15:06:53 UTC +00:00]] (1.3ms) commit transaction Redirected to

You can see it's posting the order data, but it's not putting it into the DB correctly... What did I miss?

1

1 Answers

2
votes

i think you need

form_for @delivery do |f|

  = f.fields_for :orders do |builder|
    = builder.label :info
    = builder.text_area :info
  .actions
    = f.submit

notice the f.fields_for is different