In the edit method of many controllers you initialize a new object and edit existing objects
class MagazinesController < ApplicationController
def edit
I approach this problem differently. I do not create a new object in the controller, but instead do so directly in the form.
First, to run through your controller, why are you passing the page_id as your primary params[:id]
to your Magazines controller? Looks to me that you want this:
class MagazinesController < ApplicationController
def edit
@magazine = Magazine.find(params[:id]).includes(:pages)
end
end
Then, in your magazines#edit
view, you'd do this:
%h4 Existing pages
- @magazine.pages.each do |page|
%p= link_to page, page.title
= form_for @magazine do |f|
= f.fields_for :pages, @magazine.pages.build do |builder|
= builder.text_field :title
# etc.
In that fields_for
line, you're asking for magazine-form fields for pages, but then telling it to only render the fields for a specific, new page, which you are creating on the fly with @magazine.pages.build
.
References:
fields_for
Nested Model Form Railscast (See also Part 2)