【问题标题】:Rails association in concerns关注的 Rails 协会
【发布时间】:2015-06-08 16:30:02
【问题描述】:

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

我担心的是

included do 
        has_one :auth_info 
    end

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

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

E.G

我有 3 种用户:

  1. 客户
  2. 卖家
  3. 访客

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

id_customer

但在我的情况下?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 activesupport-concern


    【解决方案1】:

    您可以通过polymorphic associations 解决这个问题(并放弃关注):

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

    【讨论】:

    • “放弃关注”是什么意思。我有很多通用方法,可以通过这种方式在所有模型之间轻松共享
    • 我的意思是,如果您的整个关注类实际上是单行的,那么您不妨删除关注。但是如果你有更多相关的代码,那么你当然可以继续关注,包括has_one关系的定义,是的。
    • 重新阅读您的问题后,也许我的回答不是您问题的最佳解决方案。对不起,我的错。
    • 你的解决方案是对的,但我有一个问题。当我执行“customer.auth_info”时,它会给我一个错误,因为查询搜索的是 customer_id 而不是 loggable.id !可能是什么问题?
    • 您是否在AuthInfo 中使用了polymorphic: true,并且您是否执行了迁移以处理多态关系? AuthInfo 需要两列才能工作:loggable_idloggable_type。请参阅文档。
    【解决方案2】:

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

    class AuthInfo < ActiveRecord::Base
      belongs_to :user
    end
    
    class User < ActiveRecord::Base
      has_one :auth_info
    end
    

    你可以的

     user = User.first
     user.auth_info 
    

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

    【讨论】:

    • 这似乎正是我想要的东西
    • 我已经在活动记录中快速搜索角色,但我找不到任何东西...你能和我分享一下你是怎么知道这件事的吗?只是好奇,并寻求提高我的搜索技能
    • 您好@ciaoben,他建议您通过创建迁移向数据库表中添加一个新列,详细信息请参见guides.rubyonrails.org/…。您需要运行“rails g migration add_role_to_users”之类的东西来创建迁移文件。然后编辑“更改”方法,添加类似“add_column :users, :role, :string”的内容。希望这会有所帮助
    • 是的,使用 Rails 迁移在用户表中创建一个名为“角色”的列
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多