ruby-on-rails – acceptable_nested_attributes_for对于has_one关系不能正常工作

我在has_one关系中遇到了accept_nested_attributes_for问题.

型号:采购和销售.

class Purchase < ActiveRecord::Base 
  has_one :sale,:dependent => :destroy
  accepts_nested_attributes_for :sale
end

class Sale < ActiveRecord::Base  
  belongs_to :purchase
end

在控制器/新动作中:

@purchase = Purchase.new(
  :club_id => @club.id,:subcategory_id => subcategory.id
)

在看法(HAML)中:

- form_for(@purchase) do |f|
  # some fields for purchase
  - f.fields_for :sale do |s|
    = s.text_field :amount,:size => 6
    # and so on

问题:在我看来,这并没有提供任何出售的输入框.购买字段呈现良好,但销售字段不显示.

如果我将这行添加到控制器:

@purchase.sale.build

我得到这个错误

undefined method `build' for nil:NilClass

为了使事情变得更加谨慎,如果我将关联类型更改为has_many而不是has_one,则创建:

class Purchase < ActiveRecord::Base 
  has_many :sales,:dependent => :destroy
  accepts_nested_attributes_for :sales
end

一切开始工作很好 – 销售字段开始出现在我的视图中,@ purchase.sales.build不会返回错误,等等.当然这并没有真正帮助我,因为它应该是has_many,而不是has_one.

任何人都可以看清这种情况吗?

解决方法

has_one构建与has_many不同
@purchase.build_sale

请参阅有关has_one http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001834的文档

Account#build_beneficiary (similar to Beneficiary.new(“account_id” => id))

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...