13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsのActiveRecordを、STI以外の目的で継承して使うときは親を抽象クラスにしないと正しく動かない

Last updated at Posted at 2013-04-24

たとえば

app/model/article/tag.rb
class Article::Tag < ::Tag
  self.table_name = 'article_tags'
  has_many :taggings, :dependent => :destroy, :class_name => 'Article::Tagging'
end
app/model/article/tagging.rb
class Article::Tagging < ::Tagging
  self.table_name = 'article_taggings'
  belongs_to :tag, :class_name => 'Article::Tag'
end

でも、うまくテーブル名の指定が効かなかった。(Rails 3.2.13)

irb(main):001:0> Article:Tag.new
ActiveRecord::StatementInvalid: Could not find table 'tags'

ググってみると

ActiveRecord Inheritance without STI?

というわけで、親クラスを抽象クラスにすることで動いた。

config/initializers/taggable.rb
Tag.module_eval do
  self.abstract_class = true
end
Tagging.module_eval do
   self.abstract_class = true
end
irb(main):001:0> Article:Tag.new
=> #<Article::Tag id: nil, name: nil>
13
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?