views:

31

answers:

1

Hello, i have a model named 'chapter' (whose only attributes are 'name' and 'course__id') which belongs to "course" (and a course has_many chapters). on the course 'Show' view, I list all chapters for that course. Easy.

I want to add a form at the end of the list so that a user can easily create a new chapter.

so in my controller, I've added this:

    @[email protected]

and the form on the view looks like this:

<% form_for([@course,@newchapter]) do |c| -%>
  <%= c.label :name, "New Chapter" %>:  <%= c.text_field :name %>
    <%= c.submit 'Create' %>
<% end %>

(for the sake of clarity: it is outside of the @course.chapters.each block)

Now, the problem is that @course.chapters.size is the actual number of chapters + the empty one i created in the controller.

Is there a way to loop through all @course.chapters except the last (empty) one? or is there a better practice (i.e. not create @newchapter or not like this)?

thanks, Pierre

A: 

You don't want to use @course.chapters.build here because this does add an empty chapter to the course. Instead you'll want to use Chapter.new and set the :course option like this.

@newchapter = Chapter.new(:course => @course)

It may not even be necessary to specify :course here depending on how you are using @newchapter.

ryanb
Thanks a lot for your quick help! the :course is indeed not even needed. I'm sure i tried it so there had to be something wrong.
Pierre
About time you showed up to stackoverflow, ryanb.
erik