[英]Rails 3.1: accepts_nested_attributes_for and has_one association - won't work?
[英]accepts_nested_attributes_for doesn't work properly for has_one relationship
我在has_one关系中遇到accepts_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
我收到此错误:
nil的未定义方法`build':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
帐户#build_beneficiary(类似于Beneficiary.new(“account_id”=> id))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.