开发者

help with accepts_nested_attributes_for in rails 3

I have the following models:

class Address < ActiveRecord::Base
  validates_presence_of :street, postal_code
end

class Person < ActiveRecord::Base
  belongs_to :address
  belongs_to :work_address, :class_name => 'Address'

  accepts_nested_attributes_for :address, :work_address

  def initialize(params={})
    params[:address] = Address.new
    params[:work_address] = Address.new
    super
  end
end

When trying to create a Person:

person = {
  "address_attributes" => {:street => "foo", :postal_code => "45632-963"}
  "work_address_attributes" => {:street => "bar", :postal_code => "45632-964"}
}
Person.create(person)

I got a person object with address fields filled, but the work_adress fields are blank. However, it works when I try:

p.work_address_attributes = {:street => "bar", :postal_code => "45632-964"}

In my view, I have the following code:

<%= form_for(@person) do |form| %>
...
<%= form.fields_for :address do |address| %>
  <%= address.text_field :street %>
  <%= address.text_field :postal_code %>
<% end %>

<%= form.fields_for :开发者_运维百科work_address do |work_address| %>
  <%= work_address.text_field :street %>
  <%= work_address.text_field :postal_code %>
<% end %>

<%= form.submit %>
<% end %>

What is wrong?


Have you tried commenting out the line in your initialize function that sets params[:work_address] to a new Address object? You shouldn't need to set it if you're using nested attributes. If you really need those two lines, I would change them to something like this:

params[:work_address] = Address.new if params[:work_address_attributes].nil?

accepts_nested_attributes_for should handle that logic for you. Perhaps your address object is overriding what you are passing in the hash?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜