Question

I'm having a difficult time understanding how to do this. I have two models, a project, and a course.

#project.rb
belongs_to :course
attr_accessible :course_id, :course
accepts_nested_attributes_for :course, reject_if: lambda { |a| a[:course_id] == 0 }

#course.rb
has_many :projects

On the Projects#new page (child object), I want to type in the name of a new course and have it create the parent object.

Here's my attempt in the view, but it doesn't seem to be working correctly.

= form_for [@user, @project] do |f|

  # Other fields

  = fields_for :course do |builder|
    = builder.label :name, 'Course Name'
    = builder.text_field :name

  = f.submit

I'll be using this parent object later to create more projects, but for now, let's assume it doesn't exist.

UPDATE 1 I've modified my fields_for to be (as per Ryan's request):

= form_for [@user, @project] do |f|

  # Other fields

  = f.fields_for :course do |builder|
    = builder.label :name, 'Course Name'
    = builder.text_field :name

  = f.submit

I'm using haml, so the = should be displaying, but the fields for does not even show up on the page, or in the generated html. Any clue as to why that is? (The submit button does display)

UPDATE 2 I've found a potential solution, but I'm not sure if it's the correct way of approaching this. In the controller, I need to build a course for the fields_for to show up.

# ProjectsController
def new
  @project  = @user.projects.new
  @project.build_course
end

# project.rb
attr_accessible :course_attributes
# So yes, I now see what you were talking about, regarding the course_attributes

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top