ruby-on-rails - 多态关联如何在 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
显示了Subscription
与imageable_type: Company
but相关联imageable_id: nil
。这是我不想添加订阅但我想添加Company
.
如果是这样,那我怎么得到imageable_id
?使用多态关联,imageable_id
@company 保存时不应该自动填充吗?
解决方案
我认为当你打电话时
@company = Company.new({:name => "Random Company Name"})
您初始化一条新记录而不保存它,这意味着它的 ID 为 nil。
当你然后打电话
@company.subscriptions.build
它不知道分配新订阅的 company_id。尝试将您的第一行更改为:
@company = Company.create({:name => "Random Company Name"})
这意味着@company 被分配了一个 ID,然后可以将其分配给订阅
推荐阅读
- ssl - 配置 Telegraf Kafka 输入 SSL
- flutter - 将数组传递给 Firestore 数据库的 orderBy 子句有什么影响?
- azure - Microsoft Azure VM 映像与 Azure Pipeline 完全相同
- c# - Docker-compose:如何将主机名用于在内部和外部都有效的 docker 实例?
- python-3.x - 根据数据帧中的时间戳运行函数
- laravel - 安装“export-laravel-5-migrations.py”插件后 mysql 工作台无法启动
- javascript - 如何使用 jQuery 从子元素中获取数据以在 xml api 中查找其他子元素?
- python - 错误:AttributeError:“_tkinter.tkapp”对象没有属性“插入”
- cfml - Cold Fusion 关闭文件 cfscript
- javascript - 如何在浏览器的控制台中使用 Javascipt 遍历虚拟 DOM?