我在rails 2.3.5中使用accepts_nested_attributes_for和has_one多态模型
class Address < ActiveRecord::Base
attr_accessible :city, :address1, :address2
belongs_to :addressable, :polymorphic => true
validates_presence_of :address1, :address2, :city
end
class Vendor < ActiveRecord::Base
attr_accessible :name, :address_attributes
has_one :address, :as => :addressable, :dependent => :destroy
accepts_nested_attributes_for :address
end
这是视图:
- form_for @vendor do |f|
= f.error_messages
%p
= f.label :name
%br
= f.text_field :name
- f.fields_for :address_attributes do |address|
= render "shared/address_fields", :f => address
%p
= f.submit "Create"
这是部分共享/地址字段.html.haml
%p
= f.label :city
%br= f.text_field :city
%span City/Town name like Dharan, Butwal, Kathmandu, ..
%p
= f.label :address1
%br= f.text_field :address1
%span City Street name like Lazimpat, New Road, ..
%p
= f.label :address2
%br= f.text_field :address2
%span Tole, Marg, Chowk name like Pokhrel Tole, Shanti Marg, Pako, ..
这是控制器:
类VendorsController<ApplicationController
def new
@vendor = Vendor.new
end
def create
@vendor = Vendor.new(params[:vendor])
if @vendor.save
flash[:notice] = "Vendor created successfully!"
redirect_to @vendor
else
render :action => 'new'
end
end
end
问题是,当我填写所有文件时,记录将按预期保存在两个表上。
但是,当我只将name和city或address1归档时,验证工作正常,显示错误消息,但我在city或address1中输入的值不会持久化,也不会显示在address表单字段中?
编辑操作也是如此。
虽然记录已保存,但地址不会显示在编辑表单上。只显示客户机模型的名称。