[英]accepts_nested_attributes_for doesn't work properly for has_one relationship
I'm having trouble with accepts_nested_attributes_for in a has_one relationship. 我在has_one关系中遇到accepts_nested_attributes_for时遇到问题。
The models: Purchase and Sale. 模特:购买和销售。
class Purchase < ActiveRecord::Base
has_one :sale, :dependent => :destroy
accepts_nested_attributes_for :sale
end
class Sale < ActiveRecord::Base
belongs_to :purchase
end
In the controller/new action: 在控制器/新动作中:
@purchase = Purchase.new(
:club_id => @club.id,
:subcategory_id => subcategory.id
)
In the view (HAML): 在视图(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
PROBLEM: this does not actually render any input boxes for sale in my view. 问题:这实际上并没有在我的视图中呈现任何待售的输入框。 The purchase fields render fine, but the sale fields do not appear. 购买字段呈现正常,但销售字段不会出现。
If I add this line to the controller: 如果我将此行添加到控制器:
@purchase.sale.build
I get this error: 我收到此错误:
undefined method `build' for nil:NilClass nil的未定义方法`build':NilClass
To make things weirder, if I change the association type to has_many instead of has_one, thus creating: 为了使事情变得更奇怪,如果我将关联类型更改为has_many而不是has_one,从而创建:
class Purchase < ActiveRecord::Base
has_many :sales, :dependent => :destroy
accepts_nested_attributes_for :sales
end
Everything starts working just fine - the sale fields start appearing in my view, @purchase.sales.build does not return an error, and so on. 一切都开始正常工作 - 销售字段开始出现在我的视图中,@ purchase.sales.build不会返回错误,依此类推。 Of course, this doesn't really help me, since it's supposed to be has_many, not has_one. 当然,这对我没有帮助,因为它应该是has_many,而不是has_one。
The has_one build is different of has_many has_one构建与has_many不同
@purchase.build_sale
See the documentation about has_one http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001834 请参阅有关has_one的文档http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001834
Account#build_beneficiary (similar to Beneficiary.new("account_id" => id)) 帐户#build_beneficiary(类似于Beneficiary.new(“account_id”=> id))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.