首页 > 解决方案 > 多态关联如何在 New 操作中获取其 imageable_id 值?

问题描述

我仍然很难处理多态关联,因为我不能做嵌套形式。然而,即使没有进入表格,我什至无法完成我认为非常基本的任务。

例如:

#app/models/user.rb
class User < ApplicationRecord
    has_many subscriptions, dependent: :destroy, as: :imageable
end

.

#app/models/company.rb
class Company < ApplicationRecord
    has_many :subscriptions, dependent: :destroy, as: :imageable
end

.

#app/models/subscription.rb
class Subscription < ApplicationRecord
    belongs_to :imageable, polymorphic: true
end

如果我运行Company.first.subscriptions.create(name: "Random"),这可行,但以下失败:

@company = Company.new({:name => "Random Company Name"})
@company.subscriptions.build
@company.save

为什么会失败?似乎是因为@company.subscriptions显示了Subscriptionimageable_type: Companybut相关联imageable_id: nil。这是我不想添加订阅但我想添加Company.

如果是这样,那我怎么得到imageable_id?使用多态关联,imageable_id@company 保存时不应该自动填充吗?

标签: ruby-on-rails

解决方案


我认为当你打电话时

@company = Company.new({:name => "Random Company Name"})

您初始化一条新记录而不保存它,这意味着它的 ID 为 nil。

当你然后打电话

@company.subscriptions.build

它不知道分配新订阅的 company_id。尝试将您的第一行更改为:

@company = Company.create({:name => "Random Company Name"})

这意味着@company 被分配了一个 ID,然后可以将其分配给订阅


推荐阅读