具有多态has_one模型的嵌套属性

时间:2010-04-29 07:38:18

标签: ruby-on-rails polymorphic-associations nested-attributes

我在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"

这是部分共享/ address_fields.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, ..

这是控制器:     class VendorsController&lt; 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

问题是当我填写所有文件时,记录按预期在两个表上保存。

但是,当我只是名称和城市或地址1提交时,验证工作,显示的错误信息,但我在城市或地址1中放置的值不会保留或不显示在地址表单字段中?

这与编辑操作的情况相同。

虽然保存了记录,但地址不会显示在编辑表单上。仅显示客户端模型的名称。 实际上,当我查看日志时,甚至根本不会查询地址模型SQL。

1 个答案:

答案 0 :(得分:1)

为什么f.fields_for :address_attributes

不应该是:

- f.fields_for :address do |address_fields|
  = render "shared/address_fields", :f => address_fields

它没有加载编辑和错误的值,因为您从未使用address_attributes的值加载@vendor.address