1

我正在为我的 Rails 应用程序使用关注点。我有不同类型的用户,所以我提出了一个loggable.rb问题。

在我的担心中,我有

included do 
        has_one :auth_info 
    end

因为我的每个包含关注点的用户都将与 auth_info 表关联。

问题是,我需要在我的 auth_info 表中放入哪些外键?

例如

我有 3 种用户:

  1. 顾客
  2. 卖方
  3. 游客

如果我只有客户,在我的表格方案中,我会放置该字段

id_customer

但在我的情况下?

4

2 回答 2

0

您可以使用多态关联来解决这个问题(并放弃关注):

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}来创建模型,也可以手动为两列创建迁移。有关更多详细信息,请参阅文档。

于 2015-06-08T18:03:23.783 回答
0

由于用户具有角色“客户”、“卖家”、“访客”。在 Users 表中添加一个名为role的列。将名为user_id的列添加到 auth_infos 表。

class AuthInfo < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_one :auth_info
end

你可以做

 user = User.first
 user.auth_info 

现在,您的关注点有了额外的逻辑。

于 2015-06-08T18:44:11.717 回答