具有多态关联的数据库设计和ActiveRecord查询

问题描述

我正在尝试设计一种数据库结构,其中用户与人之间具有各种类型的“关系”。

这些人有与之相关的活动。

我正在尝试根据与给定用户有一定关系的人来检索这些活动。

以下几行很不正确,但我认为它给出了我要了解的要点。

User.find(1).customers.join(:person).activities

同样重要的是我的查询返回了关系表上的其他属性

我想返回类似(在json中)的内容:

{
  user_id: 1,name: 'Carl',activities: {
    {
      id: 1,name: 'Swimming',relationship: 'Customer',person: {
        id: 1
        name: 'Sam',},{...}
    }
  }
}

以下是模型:

class User < ApplicationRecord
  has_many :customers
  has_many :friends
end

class Person < ApplicationRecord

end

class Relationship < ApplicationRecord
  belongs_to :user
  belongs_to :person
  # additional attributes on this model we need
end

class Customer < Relationship
  belongs_to :users
  has_many :activities
end

class Friend < Relationship
  belongs_to :users
  has_many :activities
end

class Activity < ApplicationRecord
  # Has polymorphic association 'owner'
  # owner_type (i.e. 'Customer')
  # owner_id
  belongs_to :owner,:polymorphic => true
end

有关如何获得这些关系,将数据保存在指定的联接表中的任何指导? 谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...