2016-09-21 81 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