form.html.haml 不会在 new.html.haml 上呈现



我正在研究《Agile Web Development with Rails 4》一书,我的HAML代码遇到了一些困难。

不太确定我做错了什么,但是当我去构建新产品时,我的表单没有呈现。我检查了源代码,它也不在 HTML 中,所以我的代码有问题,但不确定是什么。希望有人可以帮助我。

这是我的 Form.html.haml 代码

=if @product.errors.any?
  %div{ :id => "error_explanation" }
    %h2
      =pluralize(@product.errors.count, "error")
      prohibited this product from being saved:
    %ul
    =@product.errors.full_messages.each do |msg|
      %li 
        =msg
    %div{ :class => "field" }
      =f.label :title
      =f.text_field :title
    %div{ :class => "field" }
      =f.label :description
      =f.text_area :description, rows: 6
    %div{ :class => "field" }
      =f.label :image_url
      =f.text_field :image_url
    %div{ :class => "field" }
      =f.label :price
      =f.text_field :price
    %div{ :class => "actions" }
      =f.submit

这是我的新.html.haml

%h1 New Product
=render 'form'
=link_to 'Back', products_path

提前谢谢你。

根据meagartheTRON提供的答案以及您的最后评论:

你在哪里揭示表单对象?它似乎无处可去,因此您会收到该错误。当您通过 form_for 方法将表单绑定到模型对象时,它会生成一个表单生成器对象(f 变量)。

尝试如下操作:

<%= form_for @product, url: {action: "create"} do |f| %>
  # your code using f variable ...
<% end %>

让我们知道这是否最终修复了您的代码。

Parts需要

_前缀命名。

您的Form.html.haml必须称为_form.html.haml

除了确保表单被命名_form.html.haml之外,您还需要修复 HAML 中的一些嵌套。它应该看起来像这样:

=if @product.errors.any?
  %div{ :id => "error_explanation" }
    %h2
      =pluralize(@product.errors.count, "error")
      prohibited this product from being saved:
    %ul
    =@product.errors.full_messages.each do |msg|
      %li 
        =msg
%div{ :class => "field" }
  =f.label :title
  =f.text_field :title
%div{ :class => "field" }
  =f.label :description
  =f.text_area :description, rows: 6
%div{ :class => "field" }
  =f.label :image_url
  =f.text_field :image_url
%div{ :class => "field" }
  =f.label :price
  =f.text_field :price
%div{ :class => "actions" }
  =f.submit

您当前在表单字段上的缩进将其置于if @product.errors.any?块的范围内,这意味着表单仅在@product出现错误时才会显示。

最新更新