变化的has_many到HAS_ONE关系
问题描述:
我试图从模型关系的has_many转换到这里HAS_ONE 是我的代码变化的has_many到HAS_ONE关系
模式
class Activity < ActiveRecord::Base
has_many :product_outline_attribute, dependent: :destroy
accepts_nested_attributes_for :product_outline_attribute
end
class ProductOutlineAttribute < ActiveRecord::Base
belongs_to :activity
end
控制器
class ActivitiesController < ProductOutlinesController
def new
@activity = Activity.new
@activity.product_outline_attributes.new()
render layout: false
end
end
查看
new.html.haml
.panel
= form_for ([ @activity]), html: { class: 'ajax_form' } do |f|
= render partial: 'product_outlines/form_activity_section', locals: { f: f }
form_activity_section.html.haml
= f.fields_for :product_outline_attribute do |ff_poa|
= ff_poa.label :depth_of_knowledge
= ff_poa.select :depth_of_knowledge, DEPTH_OF_KNOWLEDGE_LEVELS.map{ |k,v| [v,k] }, prompt: (ff_poa.object.depth_of_knowledge.blank? ? 'Select Level' : nil)
用的has_many关系早些时候相同的代码工作,因为
@ activity.product_outline_attributes.new返回对象
但HAS_ONE
@ activity.product_outline_attribute是零
@ activity.product_outline_attribute.new阅读导轨引导
后引发了一个异常很有道理
有人能帮助我克服这个问题。
答
如果activity has_one product_outline_attribute。您必须通过如下代码新建一个实例:
@activity.build_product_outline_attribute