2

在我的应用程序中,我可以制作不同类型的帖子。所以,我有想法纳入Single Table Inheritance此:Rails:未初始化的常量PostsController :: TextPost

class Post < ActiveRecord::Base 
    has_many :comments 
end 

class TextPostValidator < ActiveModel::Validator 
    def validate(record) 
    if record.title.nil? and record.body.nil? 
     record.errors[:base] << "Either title or body is necessary" 
    end 
    end 
end 

class TextPost < Post 
    validates_with TextPostValidator 
end 

class ImagePost < Post 
    validates :image_url, :presence => true 
end 

class VideoPost < Post 
    validates :video_code, :presence => true 
    validates :video_service, :presence => true 
end 

class LinkPost < Post 
    validates :link_url, :presence => true 
end 

当我现在在做这在我的PostsController

def new_text 
    @post = TextPost.new 
end 

def new_image 
    @post = ImagePost.new 
end 

def new_video 
    @post = VideoPost.new 
end 

def new_link 
    @post = LinkPost.new 
end 

我得到这个错误:

uninitialized constant PostsController::TextPost 

似乎我不知道Rails的内部工作原理。

加成rails console

irb(main):009:0* ActiveRecord::Base.subclasses 
=> [Post(id: integer, title: string, body: text, video_service: string, video_code: string, image_url: string, link_url: string, ooc: boolean, nsfw: boolean, allow_comment: boolean, type: string, created_at: datetime, updated_at: datetime), 
TextPost(id: integer, title: string, body: text, video_service: string, video_code: string, image_url: string, link_url: string, ooc: boolean, nsfw: boolean, allow_comment: boolean, type: string, created_at: datetime, updated_at: datetime), 
ImagePost(id: integer, title: string, body: text, video_service: string, video_code: string, image_url: string, link_url: string, ooc: boolean, nsfw: boolean, allow_comment: boolean, type: string, created_at: datetime, updated_at: datetime), 
VideoPost(id: integer, title: string, body: text, video_service: string, video_code: string, image_url: string, link_url: string, ooc: boolean, nsfw: boolean, allow_comment: boolean, type: string, created_at: datetime, updated_at: datetime) 
LinkPost(id: integer, title: string, body: text, video_service: string, video_code: string, image_url: string, link_url: string, ooc: boolean, nsfw: boolean, allow_comment: boolean, type: string, created_at: datetime, updated_at: datetime)] 

似乎确定。

+0

@mu否它不。 – Lanbo

+0

@mu:都不行。它们也不会被'rails console'加载,但是'post.rb'位于正确的文件夹中。 'Post'被正确找到并可用。 – Lanbo

+0

'Module.constants'缺少'Post'和子类,与'Post.constants'一样。我已将“ActiveRecord :: Base.subclasses”复制到问题中。 – Lanbo

回答

5

未初始化的常量错误出现在路由错误中。尝试去你的routes.rb文件并提供单数和复数资源。

资源:后 和 资源:帖子

0

来源:http://www.hackido.com/2009/03/quick-tip-solve-uninitialized-constant.html

“事实证明,这在Ruby on Rails的最新版本走过来的重大变化之一,有几个小,小事化其中之一就是应用程序控制器不再被称为application.rb现在它被称为application_controller.rb

实际上,要解决这个问题,只需重命名该文件即可,或者如Liam指出的那样下面的评论,运行:“

耙架:更新

相关问题