Ruby 为什么不';t Rails生成器为特定模型创建属性和方法?
我的应用程序中有两个使用STI的模型:Entry和Sugar,它们非常简单 参赛作品:Ruby 为什么不';t Rails生成器为特定模型创建属性和方法?,ruby,ruby-on-rails-3,attributes,generator,sti,Ruby,Ruby On Rails 3,Attributes,Generator,Sti,我的应用程序中有两个使用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
# == 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
我通过运行rails g model Sugar amount:integer创建了Sugar模型,然后将其编辑为Entry模型的子类。迁移生成了一个金额列:
class CreateSugars < ActiveRecord::Migration
def change
create_table :sugars do |t|
t.integer :amount
t.timestamps
end
end
end
但是,“amount”属性和/或方法似乎不存在。下面是一个例子:
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 (...)
1.9.2-p290:002>s.amount=2
NoMethodError:未定义的#(…)方法'amount='
1.9.2-p290:003>s=糖。新(:数量=>2)
ActiveRecord::UnknownAttributeError:未知属性:金额(…)
为什么不提供金额属性和相关方法?STI的概念是N个模型-1个表<代码>糖
实际上正在访问表条目
,其中没有属性金额
STI的概念是N个模型-1个表Sugar
实际上正在访问表条目
,当您使Sugar从使rails使用STI(单表继承)的条目继承时,表中没有属性数量
在这个方案中,所有类都存储在基类的表(条目)中,type列存储子类的名称。因为它们都共享同一个表,所以它们也共享相同的属性:根本不使用sugars表
如果您不想这样做,您可以将条目设置为抽象类
class Entry < ActiveRecord::Base
self.abstract_class = true
end
类条目
在这种情况下,不会有entries表,但会有sugars表(Entry的每个子类都有一个)
另一种方法是将Entry和Sugar应该共享的代码放入一个模块中 当您从使rails使用STI(单表继承)的条目继承sugar时
在这个方案中,所有类都存储在基类的表(条目)中,type列存储子类的名称。因为它们都共享同一个表,所以它们也共享相同的属性:根本不使用sugars表
如果您不想这样做,您可以将条目设置为抽象类
class Entry < ActiveRecord::Base
self.abstract_class = true
end
类条目
在这种情况下,不会有entries表,但会有sugars表(Entry的每个子类都有一个)
另一种方法是将Entry和Sugar应该共享的代码放入一个模块中 STI不是应该是N个模型-1个表吗?Sugar正在访问没有属性amount的表条目。tokland-我想你是对的。。。我一发布这个问题就知道这是一个疏忽。@nilmethod:好的,作为答案发布。STI不应该是N个模型-1个表吗?Sugar正在访问没有属性amount的表条目。tokland-我想你是对的。。。我一发布这个问题就知道这是一个疏忽。@nilmethod:好的,发布为答案。
class Entry < ActiveRecord::Base
self.abstract_class = true
end