如果我有一个继承自另一个模型的模型,则不会继承关系。这似乎是有意的,但为了我的目的,我想继承这种关系。继承活跃记录关系的最佳方式是什么?
e.g。
class User
has_many :addresses
end
class OriginalUser < User
default_scope where('created_at <= ', DateTime.now - 5.years)
# how can I inherit the has_many :addresses relationship?
end
答案 0 :(得分:1)
使用Rails 4.2.4测试您的示例我发现实际 的关系是继承的。
class Address < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :addresses
end
class OriginalUser < User
end
在rails控制台中:
2.2.3 :001 > user = User.create({name: 'Martin'})
2.2.3 :002 > address = Address.create({city: 'Berlin'})
2.2.3 :003 > user.addresses << address
2.2.3 :004 > address.user
=> #<User id: 1, name: "Martin", created_at: "2015-10-09 18:15:17", updated_at: "2015-10-09 18:15:17">
2.2.3 :005 > original_user = OriginalUser.create({name: 'Steel'})
2.2.3 :006 > another_address = Address.create({city: 'Boulder'})
2.2.3 :007 > original_user.addresses << another_address
2.2.3 :008 > another_address.user
=> #<OriginalUser id: 2, name: "Steel", created_at: "2015-10-09 18:20:58", updated_at: "2015-10-09 18:20:58">
2.2.3 :009 > original_user.addresses
=> #<ActiveRecord::Associations::CollectionProxy [#<Address id: 2, city: "Boulder", user_id: 2, created_at: "2015-10-09 18:22:14", updated_at: "2015-10-09 18:22:48">]>