嵌套表单显示错误 [英] nested form display error

查看:97
本文介绍了嵌套表单显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下关于新幼儿园的表格声明

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%>

这背后的逻辑是1所幼儿园可以有多张照片.

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

以下是模型声明:

幼儿园

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

照片

  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

现在,当生成@kindergarten new时,出现以下错误:

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'

推荐答案

您编写的是@kindergarden.photos.build而不是@kindergarten.photos.build.我希望错字不在实际代码中. 也尝试@kindergarten=Kindergarten.create.如果要调用new,则只需创建一个未保存的记录,然后应调用save方法.这可能是NilClass错误的原因.

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.

这篇关于嵌套表单显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆