开发者

Submit multiple model objects from one form with Rails

开发者 https://www.devze.com 2023-04-11 11:25 出处:网络
I\'ve tried following this advice but I haven\'t succeeded yet in generating a form containing 3 objects of the same type under one submit button.

I've tried following this advice but I haven't succeeded yet in generating a form containing 3 objects of the same type under one submit button.

When I navigate to a page that should show a form containing fields for 3 objects (called elements in this example) I get the following error: undefined method 'elements' for nil:NilClass

Any pointers would be much appreciated! My code is as follows:

app/controllers/elements_controller.rb

class ElementsController < ApplicationController
  def index
    @element_group = ElementGroup.new
    render 'pages/index'
  end
end

app/views/pages/home.html.erb

<%= render 'element_groups/form'%>

app/views/element_groups/_form.html.erb

<% form_for :element_group do |f|%>
  ## The error comes from this next line, as f.object is nil
  <% f.object.elements.each do |element| %>
    <% f.fields_for element do |element_form| %>
      <%= element_form.text_field :content %>
      <%= element_form.text_field :element_type %>
      <%= element_form.text_field :subtype %>
    <% end %>
  <% end %>
<% end %>

app/models/element_group.rb

class ElementGroup
  attr_accessor :elements

  def elements
    @elements = 开发者_如何学C[]
    3.times do
      @elements << Element.new
    end
    @elements
  end
end

app/models/element.rb

class Element < ActiveRecord::Base
  attr_accessible :element_type, :subtype, :content
end

db/schema.rb

  create_table "elements", :force => true do |t|
    t.string   "element_type"
    t.string   "subtype"
    t.string   "content"
    t.datetime "created_at"
    t.datetime "updated_at"
  end


Have you tried to change to <% form_for @element_group do |f|%> ?

0

精彩评论

暂无评论...
验证码 换一张
取 消