form.html.haml无法在new.html.haml上呈现

时间:2014-01-05 07:20:52

标签: ruby ruby-on-rails-3 ruby-on-rails-4 haml

我正在使用“使用Rails 4进行敏捷Web开发”这本书,我的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

这是我的New.html.haml

%h1 New Product

=render 'form'

=link_to 'Back', products_path

提前谢谢。

3 个答案:

答案 0 :(得分:1)

根据 meagar theTRON 提供的答案以及您的上次评论:

你在哪里揭开表格对象?它似乎无处可去,因此你得到了那个错误。通过form_for方法将表单绑定到模型对象时,它会生成表单构建器对象(f变量)。

尝试以下内容:

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

如果最终修复了您的代码,请告诉我们。

答案 1 :(得分:0)

部分需要使用_前缀命名。

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

答案 2 :(得分:0)

除了确保您的表单名为_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出错时才会显示该表单。

相关问题