Rails 3 Nested Forms

前端 未结 2 2048
既然无缘
既然无缘 2020-12-25 09:47

I have a Person model and an Address Model:

class Person < ActiveRecord::Base
  has_one :address
  accepts_nested_attributes_for :address
end


class Addr         


        
相关标签:
2条回答
  • 2020-12-25 10:00

    Why is your address built in your new action, and not in the create action? You're building an address from a non saved model, without an id, so the foreign key can't be set. You should keep your @person in your new action, but put your build_address in your create action, after @person has been saved.

    0 讨论(0)
  • 2020-12-25 10:05

    You need to have accepts_nested_attributes_for :address on your Person model for this to work nicely. In your create action you can then do this:

    def create
      @person = Person.new(params[:person])
      ...
    end
    

    Then Rails will take care of the rest.

    UPDATE: if the address_id column is in the people table then it should be belongs_to :address, not has_one :address

    0 讨论(0)
提交回复
热议问题