nested form display error

喜你入骨 提交于 2019-12-11 18:01:59

问题


I have the following form declaration for a new kindergarten

<%= form_for @kindergarten, :html => {:multipart => true}  do |f|%>

            <%= render 'shared/error_messages', object: f.object %>
        </br>   
            <%= f.fields_for :photos do |p| %>
                <%= p.label 'upload photo'%>
                <%= p.file_field :image %>
            <% end %>
        </br>
            <%= render 'about_company', f: f%>
        </br>
            <%= render 'contact', f: f %>
            <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
        <%end%>

The logic behind this is that 1 kindergarten can have multiple photos.

Here are the model declarations:

Kindergarten

has_many :photos, limit: 7, dependent: :destroy   
accepts_nested_attributes_for :photos

Photo

  attr_accessible :image, :logo, :kindergarten_id
  belongs_to :kindergarten
  mount_uploader :image, ImageUploader

  validates :kindergarten_id, presence: true
  validates :image, presence: true

And here's how the kindergartens controller looks like:

  def new
    @kindergarten = Kindergarten.new
    @kindergarden.photos.build
  end

Now, when @kindergarten new is generated i get the following error:

undefined method 'photos' for nil:NilClass

Application Trace | Framework Trace | Full Trace
app/controllers/kindergartens_controller.rb:5:in `new'

回答1:


You've written @kindergarden.photos.build instead of @kindergarten.photos.build. I hope the typo is not in the actual code. Also try @kindergarten=Kindergarten.create . If you are calling new just creates an unsaved record, which should be followed by a call to the save method. That could be the reason for the NilClass error.



来源:https://stackoverflow.com/questions/12547543/nested-form-display-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!