0

因此,我正在学习 MHartl Rails 教程,到目前为止,它一直很棒,尽管我刚刚遇到了第一个错误,并且找不到有效的解决方案。

错误:

 NoMethodError in Users#new

Showing /Users/myname/Sites/rails_projects_updated/first_app/app/views/users/new.html.erb where line #6 raised:

undefined method `model_name' for NilClass:Class

Extracted source (around line #6):

3: 
4: <div class="row">
5:   <div class="span6 offset3">
6:     <%= form_for(@user) do |f| %>
7: 
8:       <%= f.label :name %>
9:       <%= f.text_field :name %>

新的.html.erb:

<% provide(:title, 'Sign up') %>
<h1>Sign up</h1>

<div class="row">
  <div class="span6 offset3">
    <%= form_for(@user) do |f| %>

      <%= f.label :name %>
      <%= f.text_field :name %>

      <%= f.label :email %>
      <%= f.text_field :email %>

      <%= f.label :password %>
      <%= f.password_field :password %>

      <%= f.label :password_confirmation, "Confirmation" %>
      <%= f.password_field :password_confirmation %>

      <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
    <% end %>
  </div>
</div>

和用户控制器

class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])
  end

   def create
      @user = User.new(params[:user])
      if @user.save
        # Handle a successful save.
      else
        render 'new'
      end
    end
  end

任何帮助,将不胜感激!谢谢。

4

1 回答 1

1

当然,您的控制器中缺少以下方法:

 def new
    @user = User.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @user }
    end
  end

正在发生的事情是,当表单响应创建操作并点击render 'new'您在此问题中没有的操作时。因此,当new呈现操作时,它会执行@user = User.new这将使您能够创建新用户。

于 2013-04-17T18:22:44.360 回答