您可以使用多态关联来解决这个问题(并放弃关注):
class AuthInfo < ActiveRecord::Base
belongs_to :loggable, polymorphic: true
end
class Customer < ActiveRecord::Base
has_one :auth_info, as: :loggable
end
class Seller < ActiveRecord::Base
has_one :auth_info, as: :loggable
end
class Visitor < ActiveRecord::Base
has_one :auth_info, as: :loggable
end
现在您可以检索:
customer.auth_info # The related AuthInfo object
AuthInfo.first.loggable # Returns a Customer, Seller or Visitor
您可以使用rails g model AuthInfo loggable:references{polymorphic}
来创建模型,也可以手动为两列创建迁移。有关更多详细信息,请参阅文档。