views:

59

answers:

1

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
A: 

I'm not 100% sure what you're asking, but if you're trying to instantiate a new magazine, with many magazinepages, you'll need to iterate over each magazine page. Something like this:

def create
  @magazine = Magazine.new(params[:magazine])
  if params[:magazinepages]
    params[:magazinepages].each do |page|
      @magazine.magazinepages.build(page)
    end
  end

  # Save the model, do your redirection or rendering invalid model etc
end
nfm
I know it can be done that way, but I wanted to reduce the number of lines, so that I had only a single line in the create action
kristian nissen