使用 Rails 和 HAML 时,我收到错误:nil:NilClass 的未定义方法 'name'



我是rails的新手,在Action 3中基于rails设置ticketee项目,我试图稍微偏离并使用view/projects/show.html.haml 设置haml

我确实配置了Gemfile并安装了haml,我测试了一个基本的haml页面,它确实可以工作。

这是我的问题,在将show.html.erb迁移到haml时,我遇到了一个无法解决的错误。

show.html.erb:

<h1>lt;%=@项目名称%><h1>

如果我转到http://localhost:3000/projects/1它显示id为1的项目名称。

show.html.haml:

%h2= @project.name

After I replace show.html.erb with the haml and I go to the above url I get:

NoMethodError in Projects#show

Showing /ticketee/app/views/projects/show.html.haml where line #1 raised:

undefined method `name' for nil:NilClass Extracted source (around line #1):

1: %h2= @project.name Rails.root: /ticketee

Application Trace | Framework Trace | Full Trace app/views/projects/show.html.haml:1:in `_app_views_projects_show_html_haml___2329513113615295829_70311891362660'

The schema.rb definitely has the name field:

ActiveRecord::Schema.define(:version => 20120212051007) do
    create_table "projects", :force => true do |t|
        t.string   "name"
        t.datetime "created_at", :null => false
        t.datetime "updated_at", :null => false
    end
end

我的控制器:

class ProjectsController < ApplicationController
    def index
    end
    def new
        @project = Project.new
    end
    def create
        @project = Project.new(params[:project])
        @project.save
        #flash[:notice] = "Project has been created."
        redirect_to @project, :notice => "Project has been created."
    end
end

我想这只是我的疏忽,因为这是haml的一个非常基本的用法。

您的Project控制器中似乎没有show方法。由于projects/1意味着它是一个特定的记录,所以会调用show页面。当调用/projects时,将调用index方法。

一种可能的显示方法是:

  def show
    @project = Project.find(params[:id])
  end

在这种方法中,一个实例变量被分配给@project,ID在URL中。这可能是你问题的答案!

相关内容

最新更新