2015-11-25 55 views
0

如果我们有3种型号=>客户,用户和物与另一种模型业主这就是从用户继承,我们试图建立一个has_many through协会这样的:的Rails通过与传承问题关联的has_many

class Customer < ActiveRecord::Base 
has_many :things, :dependent => :destroy 
has_many :owners, through: :things 
end 

class Thing < ActiveRecord::Base 
belongs_to :customer, foreign_key: "customer_id" 
belongs_to :owner, foreign_key: "owner_id" 
end 

class Owner < User 
has_many :things, :dependent => :destroy 
has_many :customers, through: :things 
end 

为什么会@owner.things不为我们工作? (@owner是所有者的一个实例)。它给出了undefined method "things"错误。

@owner是current_user,但是如何将其指定为User的实例?

是将owner_id更改为user_id的唯一解决方案,还是有更好的解决方案吗?

+0

'@ owner'的值是多少? – linkyndy

+0

你确定'@ owner'是'Owner'的一个实例吗? – linkyndy

+0

糟糕,是啊,它是current_user – tilin

回答

0

如您所述,current_userUser的一个实例,不是其子类Owner

如果你想这种关系添加到current_user,您可以将其添加到其类,User,而不是Owner

class User < ActiveRecord::Base # or whatever superclass you have for User 
    has_many :things, dependent: :destroy 
end 

否则,如果你想坚持到Owner,你应该覆盖创建current_user,以便它使用Owner类而不是User

+0

好的,但它仍然要求在表中有user_id事情吗? – tilin

+0

是否必须在Things表中将owner_id更改为user_id?这是问题和唯一的选择吗? – tilin

+0

这取决于您选择哪种方法。如果你只使用'User'并去掉'Owner',当然你需要'user_id'。如果将'has_many:things'关系添加到'User',则可以在'Thing'中设置反向'belongs_to:user'并在'things'中使用'user_id'列。除非另有说明,用户has_many:things'默认在'things'表中预计有'user_id'列。 – linkyndy