Ruby on rails RubyonRails-默认对象类型取决于模型
假设我有一个帖子模型,可以是一篇文章,也可以是视频 这是我的帖子模型:Ruby on rails RubyonRails-默认对象类型取决于模型,ruby-on-rails,ruby,Ruby On Rails,Ruby,假设我有一个帖子模型,可以是一篇文章,也可以是视频 这是我的帖子模型: Post(id:integer,user\u id:integer,Post\u类型:string,创建时间:datetime,更新时间:datetime) 因此,我: 课堂文章
Post(id:integer,user\u id:integer,Post\u类型:string,创建时间:datetime,更新时间:datetime)
因此,我:
课堂文章
课堂视频
Article.create
,自动将post\u type
设置为“Article”
Article.all
,仅显示post\u type==“Article”
视频模型也是如此。您可以使用单表继承(STI) 您可以将列
post_type
更改为type
,以接近rails
默认值
或者,您可以按如下方式定义自定义继承_列:
class Post < ActiveRecord::Base
self.inheritance_column = 'post_type'
end
class Article < Post
end
class Video < Post
end
class Post
然后rails
在type
或post\u type
列中保存文章
或视频
信息
有关更多信息,请参阅。您可以使用单表继承(STI) 您可以将列
post_type
更改为type
,以接近rails
默认值
或者,您可以按如下方式定义自定义继承_列:
class Post < ActiveRecord::Base
self.inheritance_column = 'post_type'
end
class Article < Post
end
class Video < Post
end
class Post
然后rails
在type
或post\u type
列中保存文章
或视频
信息
有关更多信息,请参阅。在文章模型中添加此选项以自动分配帖子类型:
def initialize
super
self.post_type = :article
end
然后还添加自动筛选的默认范围:
default_scope -> { where(post_type: :article) }
在视频模型中添加相同的内容,但将:article更改为:Video除外。在文章模型中添加以下内容以自动分配帖子类型:
def initialize
super
self.post_type = :article
end
然后还添加自动筛选的默认范围:
default_scope -> { where(post_type: :article) }
将相同内容添加到视频模型,但将:文章更改为:视频除外