Rails通过与继承问题相关联来解决问题

时间:2015-11-25 21:35:03

标签: ruby-on-rails ruby

如果我们有3个型号=>客户,用户和事物以及另一个模型所有者继承自用户,我们尝试创建这样的has_many through关联:

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的解决方案还是有更好的解决方案?

1 个答案:

答案 0 :(得分: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