In my App, I have different kinds of posts people can make. So I had the idea to incorporate the Single Table Inheritance for this:
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
And when I now do this in my PostsController
:
def new_text
@post = TextPost.new
end
def new_image
@post = 开发者_如何学JAVAImagePost.new
end
def new_video
@post = VideoPost.new
end
def new_link
@post = LinkPost.new
end
I get this error:
uninitialized constant PostsController::TextPost
It seems I know not enough about the inner workings of Rails to find out why.
Addition
From the 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)]
Seems ok.
An uninitialized constant error comes under a Routing Error. Try going to your routes.rb file and offering both singular and pluralized resources.
resources :post and resources :posts
From : http://www.hackido.com/2009/03/quick-tip-solve-uninitialized-constant.html
"Turns out, among the Major changes that came along with the latest Release of Ruby on Rails, there were a few minor ones too. One of those is that the application controller is no longer called application.rb Now it's referred to as application_controller.rb.
In effect, to solve this problem, just rename the file. Or, as Liam points out in the comments below, run:"
rake rails:update
精彩评论