Nested model form with collection in Rails 2.3

Posted by kristian nissen on Stack Overflow See other posts from Stack Overflow or by kristian nissen
Published on 2009-08-20T18:32:07Z Indexed on 2010/05/16 15:10 UTC
Read the original article Hit count: 216

Filed under:

How can I make this work in Rails 2.3?

class Magazine < ActiveRecord::Base
  has_many :magazinepages
end

class Magazinepage < ActiveRecord::Base
  belongs_to :magazine
end

and then in the controller:

def new
  @magazine = Magazine.new
  @magazinepages = @magazine.magazinepages.build
end

and then the form:

<% form_for(@magazine) do |f| %>
  <%= error_messages_for :magazine %>
  <%= error_messages_for :magazinepages %>
  <fieldset>
    <legend><%= t('new_magazine') %></legend>
      <p>
        <%= f.label :title %>
        <%= f.text_field :title %>
      </p>
      <fieldset>
        <legend><%= t('new_magazine_pages') %>
          <% f.fields_for :magazinepages do |p| %>
            <p>
              <%= p.label :name %>
              <%= p.text_field :name %>
            </p>
            <p>
              <%= p.file_field :filepath %>
            </p>
          <% end %>
      </fieldset>
    <p>
      <%= f.submit :save %>
    </p>
  </fieldset>
<% end %>

problem is, if I want to submit a collection of magazinepages, activerecord complaints because it's expected a model and not an array.

create action:

def create
  @magazine = Magazine.new params[:magazine]
  @magazine.save ? redirect_to(@magazine) : render(:action => 'new')
end

© Stack Overflow or respective owner

Related posts about ruby-on-rails