Lan*_*nbo 2 ruby ruby-on-rails single-table-inheritance ruby-on-rails-3
在我的应用程序中,我可以使用不同类型的帖子.所以我有想法为此包含单表继承:
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
Run Code Online (Sandbox Code Playgroud)
当我现在这样做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
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
uninitialized constant PostsController::TextPost
Run Code Online (Sandbox Code Playgroud)
我似乎对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)]
Run Code Online (Sandbox Code Playgroud)
好像没问题.
| 归档时间: |
|
| 查看次数: |
15844 次 |
| 最近记录: |