【问题标题】:nested attributes with polymorphic has_one model具有多态 has_one 模型的嵌套属性
【发布时间】:2010-04-29 07:38:17
【问题描述】:

我在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, ..

这是控制器: 类 VendorsController

  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都没有查询到。

【问题讨论】:

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


    【解决方案1】:

    为什么是f.fields_for :address_attributes

    不应该是:

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

    它不会加载编辑和错误时的值,因为您从未使用来自 @vendor.address 的值加载 address_attributes

    【讨论】:

    • 如果我只使用:address 而不是:address_attributes,在新表单上,我只会看到客户端name 字段。地址字段未显示。因此,如 RailsCasts epi-196 所示,在控制器上它说要像 @vendor.address.build 一样创建孩子我收到此错误 gist.github.com/384010
    • 这里是传递给创建方法的参数:Processing VendorsController#create (for 127.0.0.1 at 2010-04-30 00:32:03) [POST] 参数:{"commit"=> "创建", "authenticity_token"=>"5KQpowfKMWCc/FUXWjXnDNL9F/vBnnOXnCkWvXeSFA8=", "vendor"=>{"name"=>"", "address_attributes"=>{"city"=>"Kathmandu", "address1" =>"", "address2"=>""}}}
    • 你想要@vendor.build_address(因为这是一对一的关系)
    • 谢谢,这就是解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多