2013-09-30 22 views
9

我在訪問Rails 4中的/users/new時出現錯誤Unable to autoload constant UsersController, expecting /app/controllers/users_controller.rb to define it無法自動加載常量UsersController

這裏是控制器代碼

class UserController < ApplicationController 
    def new 
     @user = User.new 
    end 

    def create 
     @user = User.new(params[:user]).permit(:email, :password,:password_confirmation) 

     respond_to do |format| 
     if @user.save 
     format.html { redirect_to new_user_path, notice: 'User was successfully created.' } 
     format.json { render action: 'show', status: :created, location: @user } 
     else 
     format.html { render action: 'new' } 
     format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 
     end 
    end 
    end 

而對於new.html.erb我的觀點是:

<h1>Sign up</h1> 

    <%= form_for(@user) do |f| %> 

    <% if @user.errors.any? %> 
     <div id="error_explanation"> 
     <h2><%= pluralize(@user.errors.count, "error") %> prohibited this post from being  saved:</h2> 

     <ul> 
      <% @user.errors.full_messages.each do |msg| %> 
      <li><%= msg %></li> 
      <% end %> 
     </ul> 
    </div> 
    <% end %> 
    <div class="field"> 
    <%= f.label :email %><br> 
    <%= f.text_field :email %> 
    </div> 
    <div class="field"> 
    <%= f.label :password %><br> 
    <%= f.password_field :password %> 
    </div> 
    <div class="field"> 
    <%= f.label :password_confirmation, "Confirmation" %> 
    <%= f.password_field :password_confirmation %> 
    </div> 
    <div class="actions"> 
    <%= f.submit "Create my account" %> 
    </div> 
<% end %> 

User型號:

class User < ActiveRecord::Base 
    has_many :projects 
    has_many :pledges 
    has_many :posts 
    has_many :comments 
end 
+6

變化'UserController'到'UsersController'(在軌慣例,控制器名稱應該是資源的多元化的形式)。 –

+0

謝謝@ZachKemp。它爲我工作。 – Preethika

回答

14

Rails的預計是複數控制器名稱。您發佈的第一個文件內容的第一行寫爲奇:

/app/controllers/users_controller.rb您有:

用戶控制器<的ApplicationController

相反,它應該是:

用戶控制器<的ApplicationController


Rails Guide提供了你的路由文件中定義的資源的例子。此外,還有一個信息說明,解釋了使用resource方法定義路線將始終映射到控制器的複數名稱。

這是本指南的信息說明。

因爲您可能希望對單數路線(/帳戶)和複數路線(/ accounts/45)使用相同的控制器,所以單數資源映射到多個控制器。例如,資源:照片和資源:照片創建映射到相同控制器(PhotosController)的單數和複數路線。

來源:Resource Routing: The Rails Default

+0

您能否引用您的「Rails期望控制器名稱被複數化」的來源。 – yekta

+0

@yekta我添加了一些額外的信息與來源。這強調了多元化控制器是常規的事實。這些信息被埋在旁邊。多元化貫穿整個指南,Rails本身。可以覆蓋默認值並使用單個控制器。 – sealocal

+0

感謝您的來源。雖然多元化並沒有解決我的問題。在我的情況下,我在ApplicationController中使用'unloadable',將其解決。 – yekta