1

我的应用程序中有两个使用 STI 的模型:Entry 和 Sugar,它们非常简单。

参赛作品:

# == Schema Information
#
# Table name: entries
#
#  id         :integer         not null, primary key
#  created_at :datetime        not null
#  updated_at :datetime        not null
#  user_id    :integer
#  type       :string(255)
#

class Entry < ActiveRecord::Base
  # attr_accessible :title, :body
  belongs_to :user
end

糖(请注意注释宝石中缺少amount架构信息):

# == Schema Information
#
# Table name: entries
#
#  id         :integer         not null, primary key
#  created_at :datetime        not null
#  updated_at :datetime        not null
#  user_id    :integer
#  type       :string(255)
#

class Sugar < Entry
  attr_accessible :amount
end

我通过运行创建了 Sugar 模型rails g model Sugar amount:integer,然后将其编辑为 Entry 模型的子类。生成的迁移创建了一个金额列:

class CreateSugars < ActiveRecord::Migration
  def change
    create_table :sugars do |t|
      t.integer :amount

      t.timestamps
    end
  end
end

该列存在于我的数据库中:

bridges_development=# \d sugars
                                     Table "public.sugars"
   Column   |            Type             |                      Modifiers                      
------------+-----------------------------+-----------------------------------------------------
 id         | integer                     | not null default nextval('sugars_id_seq'::regclass)
 amount     | integer                     | 
 created_at | timestamp without time zone | not null
 updated_at | timestamp without time zone | not null
Indexes:
    "sugars_pkey" PRIMARY KEY, btree (id)

但是,“数量”属性和/或方法似乎不存在。这是一个例子:

1.9.2-p290 :002 > s.amount = 2
NoMethodError: undefined method `amount=' for #<Sugar:0xb84041c> (...)

1.9.2-p290 :003 > s = Sugar.new(:amount => 2)
ActiveRecord::UnknownAttributeError: unknown attribute: amount (...)

为什么不提供amount属性和相关方法?

4

2 回答 2

1

当您从使 rails 使用 STI(单表继承)的条目中继承糖时

在此方案中,所有类都存储在基类的表(条目)中,类型列存储子类的名称。因为它们都共享同一张表,所以它们也共享相同的属性:根本不会使用sugars 表

如果你不想要这个,你可以让 entry 成为一个抽象类

class Entry < ActiveRecord::Base
  self.abstract_class = true
end

在这种情况下,将没有条目表,但会有一个糖表(并且每个条目的其他子类都有一个)。

另一种方法是将Entry 和Sugar 应该共享的代码放入一个模块中。

于 2012-05-23T20:21:48.533 回答
0

STI 的想法是 N 个模型 - 1 个表。Sugar实际上是访问表entries,没有属性amount

于 2012-05-23T20:21:16.627 回答