在我的应用程序中,我有不同类型的帖子,人们可以做。所以我想把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)]

似乎可以。

最佳答案

未初始化的常量错误属于路由错误。尝试转到routes.rb文件并提供单一和多元化的资源。
资源:员额

资源:员额

07-26 09:35