【发布时间】:2018-03-14 17:42:08
【问题描述】:
我有以下上下文:
4 种型号:
- 项目
- 投资者
- 订阅
- 外部订阅
一个project 应该有许多investors 到subscriptions 或external_subscriptions。
我目前有一个方法可以做这样的事情:Investor.where(id: (subscription_ids + external_subscription_ids))。
我的目标是建立has_many 关系(并精确地使用has_many activerecord 功能)以获得相同的结果。
我怎样才能做到这一点?有没有可能?
谢谢!
Project
[Associations]
has_many :subscriptions
has_many :external_subscriptions
[Table description]
create_table "projects", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Investor
[Associations]
has_many :subscriptions
has_many :external_subscriptions
[Table description]
create_table "investors", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Subscription
[Associations]
belongs_to :project
belongs_to :investor
[Table description]
create_table "subscriptions", force: :cascade do |t|
t.integer "project_id"
t.integer "investor_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["investor_id"], name: "index_subscriptions_on_investor_id"
t.index ["project_id"], name: "index_subscriptions_on_project_id"
end
ExternalSubscription
[Associations]
belongs_to :project
belongs_to :investor
[Table description]
create_table "external_subscriptions", force: :cascade do |t|
t.integer "project_id"
t.integer "investor_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["investor_id"], name: "index_external_subscriptions_on_investor_id"
t.index ["project_id"], name: "index_external_subscriptions_on_project_id"
end
我在 Rails 5.0.x
编辑
我的真实模型比这更复杂。在这里,我只是展示关系以便于讨论,但我不能将subscriptions 和external_subscriptions 合并到同一个模型中。
【问题讨论】:
-
Subscription和ExternalSubscription的表结构相同。您可以使用单表继承 (edgeguides.rubyonrails.org/…) 或简单的subscription_type枚举字段来创建两个单独的 has_many 关系subscriptions、external_subscriptions以及all_subscriptions。 -
可以使用 SQL VIEW 在两个表上执行
UNION ALL,然后has_many through该视图来实现 -
表格是一样的。也许您只需要在订阅表上对该表进行判别(如布尔标志
external),然后相应地更新您的逻辑。
标签: ruby-on-rails activerecord