ruby-on-rails – acceptable_nested_attributes_for对于has_one
发布时间:2020-12-16 19:47:34 所属栏目:百科 来源:网络整理
导读:我在has_one关系中遇到了accept_nested_attributes_for问题. 型号:采购和销售. class Purchase ActiveRecord::Base has_one :sale,:dependent = :destroy accepts_nested_attributes_for :saleendclass Sale ActiveRecord::Base belongs_to :purchaseend 在
我在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的文档
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |