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指出的那樣下面的評論,運行:「

耙架:更新

相關問題