如何自定义 Rails 3 STI 列名 [英] How to customize Rails 3 STI column name
问题描述
我有一个名为 Post
的类:
I have a class named Post
:
class Post < ActiveRecord::Base
end
我有一个名为 Question
的类,它继承自 Post
:
I have a class named Question
that inheriting from Post
:
class Question < Post
end
我有一个名为 Answer
的类,它也继承自Post":
and I have a class named Answer
that also inheriting from 'Post':
class Answer < Post
end
在Post
中,我有一个名为post_type_id
的列,其类型为Integer
.
我如何使用 STI 和特定的列名 &类型继承自 Post?0
表示Question
,1
表示Answer
.(0 & 1 是posts表中post_type_id
的值)
In Post
, I have a column named post_type_id
and its' type is Integer
.
How do I use STI and specific column name & type to inherit from Post? 0
means Question
and 1
means Answer
. (0 & 1 is the value of post_type_id
in posts table)
推荐答案
您可以像这样更改单表继承列的名称:
You can change the name of the single table inheritance column like so:
class Post < ActiveRecord::Base
self.inheritance_column = 'type_column_name'
end
但是,没有办法让 Rails 使用整数而不是将实际类型存储为字符串,这让我觉得这可能不是单目标继承的好用例.也许范围更适合您:
However, there is no way to cause Rails to use integers instead of storing the actual type as a string, which makes me think that this may not be a great use case for single target inheritance. Perhaps a scope would suit you better instead:
class Post < ActiveRecord::Base
scope :questions, where(:post_type_id => 0)
scope :answers, where(:post_type_id => 1)
end
@questions = Post.questions.all
@answers = Post.answers.all
这篇关于如何自定义 Rails 3 STI 列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!