2016-09-21 27 views
0

我使用user_types模型(id和type作爲字符串)描述的可以具有不同特權的用戶模型構建應用程序。由於我工作軌測試,我得到錯誤Rails無法自動加載常量user_type

LoadError: Unable to autoload constant User_type, expected app/models/user_type.rb to define it 

這裏是我的模型:

class UserType < ActiveRecord::Base 
    belongs_to :user 
    validates :type, presence: true, length: { maximum: 100 } 
end 

下面是控制器和測試文件

class UserTypeController < ApplicationController 
    def index 
     @user_type = User_type.all 
    end 
    def new 
     @user_type = User_type.build(user_type_params) 
    end 
    private 
    def user_type_params 
     params.require(:user_type).permit(:type) 
    end 
end 

測試模式:

require 'test_helper' 

class UserTypeTest < ActiveSupport::TestCase 
    # test "the truth" do 
    # assert true 
    # end 
    def setup 
    @user_type = User_type.new(id:2,type:"test") 
    end 
    test "is_valid" do 
    assert @user_type.valid? 
    end 

end 

我想做一些基本的「is_va蓋「測試,我得到了上述錯誤。我還刪除了最後一個模型「user_type」,並將其創建爲「UserType」,但它沒有起作用。

+0

您的UserType模型位於app/models/user_type.rb中嗎? –

回答

0

您的模型的類名是UserTypeUser_type沒有在任何地方定義。您可以保持模型名稱不變,並修復測試和控制器,或重命名模型名稱。前者是Rails約定,所以我建議你去那個(CamelCased名字)。

+0

好的,但是: 1)那是User_type型號名稱,我之前剛更改過它 2)使用@ UserType = UserType.new後出現此錯誤: ActiveRecord :: SubclassNotFound:無效的單表繼承類型:測試不是UserType的子類 – andrey

+0

'type'是默認的屬性名稱,如果要實現單表繼承。您可以將您的列和屬性訪問器重命名爲其他內容(例如'kind'),或者您可以更改繼承列。請參閱:http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-inheritance_column – Teoulas

0

在整個控制器和測試中,您使用User_type.all,User_type.build,User_type.new,但您的型號名爲UserType

0

變化在課堂上,並從該UserType模型的表中定義刪除type列或將其重命名爲類似user_type因爲這是一個保留的列名的型號,以UserType,可用於唯一的單表繼承。

+0

我得到這個:NoMethodError:未定義的方法'類型'爲#<用戶類型:0x00561ec2341fc0> 測試/模型/user_type_test.rb:11:in'block in '我的user_type測試:def setup \t @UserType = UserType.new(id:2,description:「test」) end test「check」do \t assert @ UserType.valid? 結束 – andrey

+0

您是否正確使用遷移重命名了「type」列?並從各處刪除'type'的用法,包括'UserType'控制器(在user_type_params中)和模型(即在存在驗證中)? – Sajan