以下是我正在尝试做的事情:
class Account < ActiveRecord::Base
def name
end
end
class TypeA < Account
end
class TypeB < Account
end
其中TypeA和TypeB存储在两个不同的表上,而Account几乎充当抽象接口(没有关联的表)。它们都有大量的字段和大量的字段,所以我想让它们分开。有办法解决这个问题吗?
(上面的例子不适用于帐户的表格,预计顺便说一下。)
更新
现在,如果我使用模块(如答案中所示),则会引发另一个问题:
假设我有
class Transaction < ActiveRecord::Base
belongs_to :account, :polymorphic => true
end
帐户可以是TypeA
或TypeB
。我得到以下不当行为:
i = TypeA.new(:name => "Test")
t = Transaction.new(:account => i)
t.account.name
>> nil
这不是我想要的account.name
应该返回“测试”。怎么弄这个?
答案 0 :(得分:1)
使用模块代替。您在要共享的两个模型之间共享行为。这是模块的一个很好的用例。
# inside lib/account.rb
module Account
# ...
def name
# code here
end
# ...
end
# inside app/models/type_a.rb
class TypeA < ActiveRecord::Base
include Account
end
# inside app/models/type_b.rb
class TypeB < ActiveRecord::Base
include Account
end