Reputation: 595
I'm trying to convert models from has_many relation to has_one here is my code
models
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
controller
class ActivitiesController < ProductOutlinesController
def new
@activity = Activity.new
@activity.product_outline_attributes.new()
render layout: false
end
end
View
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 )
earlier same code with has_many relation works because
@activity.product_outline_attributes.new returns an object
but with has_one
@activity.product_outline_attribute is nil
@activity.product_outline_attribute.new raises an exception
it makes sense after reading rails guide
Could someone help me on overcoming this issue.
Upvotes: 0
Views: 152
Reputation: 571
If activity has_one product_outline_attribute. You must new an instance by codes like this:
@activity.build_product_outline_attribute
Upvotes: 2