在我的應用程序中,我可以製作不同類型的帖子。所以,我有想法納入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)]
似乎確定。
@mu否它不。 – Lanbo
@mu:都不行。它們也不會被'rails console'加載,但是'post.rb'位於正確的文件夾中。 'Post'被正確找到並可用。 – Lanbo
'Module.constants'缺少'Post'和子類,與'Post.constants'一樣。我已將「ActiveRecord :: Base.subclasses」複製到問題中。 – Lanbo