[英]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.