在我的应用程序中,我可以发布不同类型的帖子。所以我有想法将Single Table Inheritance纳入其中:
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 :(得分:5)
路由错误导致未初始化的常量错误。尝试转到routes.rb文件并提供单数和复数资源。
资源:发布 和 资源:帖子
答案 1 :(得分:0)
来自:http://www.hackido.com/2009/03/quick-tip-solve-uninitialized-constant.html
“事实证明,在Ruby on Rails的最新版本中出现的主要变化中,还有一些小的变化。其中一个是应用程序控制器不再被称为application.rb现在它被称为as application_controller.rb。
实际上,要解决此问题,只需重命名该文件即可。或者,正如Liam在下面的评论中指出的那样,运行:“
rake rails:update