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:
@newchapter=@course.chapters.build
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
You don’t want to use
@course.chapters.buildhere because this does add an empty chapter to the course. Instead you’ll want to useChapter.newand set the:courseoption like this.It may not even be necessary to specify
:coursehere depending on how you are using@newchapter.