How do you reference only the persisted records in an active record association

后端 未结 6 542
一生所求
一生所求 2020-12-10 14:05

In the edit method of many controllers you initialize a new object and edit existing objects

class MagazinesController < ApplicationController
   def edit         


        
6条回答
  •  离开以前
    2020-12-10 14:46

    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)

提交回复
热议问题