Search code examples
ruby-on-railsnestedsimple-formbelongs-to

Rails :: in nested model form, update belongs_to "parent" attributes


I am building a Rails application and I am in front of an issue with form I can't fix. I have an order model which belongs_to customer so when I build the form I do @order = @customer.orders.build

This works well to save orders attributes but I also want to update customer attributes as well which never work.

How can I save order and update "parent" customer attributes in the same process ?

Thanks for your help !

Edit:

Customer model:

class Customer < ActiveRecord::Base
  has_many :orders
end

Order model:

class Order < ActiveRecord::Base
  belongs_to :customer
  accepts_nested_attributes_for :customer
end

My project:

  • Ruby On Rails 4.2.6 / Ruby 2.2.2
  • Devise 3.5.9
  • Simple form 3.1.0

Solution

  • You should update your customer in your create method. How about:

        def create
            @order = current_customer.orders.build order_params
            if @order.save
              @order.customer.update_attributes(order_params[:customer_attributes])
              ...
            else
              ...
            end
          end