1

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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

you are welcome - I see you are fairly new here so may not know that you should accept whatever you think is the correct answer. This helps others who are googling, and enhances the answers reputation.
Done - it wouldn't let me do it for 10 minutes for some reason but it has worked now!
Made the same mistake. Good catch!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.