ruby-on-rails - rails:如何通过 Join Table 链接两个 ActiveRecord
问题描述
我有两个模型(服务,配置文件),它们通过连接表相互关联,有一个 has_many。
class Service < ApplicationRecord
has_many :service_profiles, dependent: :destroy
has_many :profiles, :through => :service_profiles
end
class Profile < ApplicationRecord
has_many :service_profiles, dependent: :destroy
has_many :services, :through => :service_profiles
end
class ServiceProfile < ApplicationRecord
belongs_to :service
belongs_to :profile
end
我通过 CLI 创建了一个服务和一个配置文件,现在想通过加入表链接这两者。我想做这样的事情,但找不到答案:
2.6.3 :016 > profile = Profile.first
Profile Load (12.3ms) SELECT "profiles".* FROM "profiles" ORDER BY "profiles"."id" ASC LIMIT $1 [["LIMIT", 1]]
=> #<Profile id: 1, name: "awesome Policy", description: "awesome Policy for awesome devices", created_at: "2020-05-26 08:56:08", updated_at: "2020-05-26 08:56:08">
2.6.3 :017 > profile.services.first.link
解决方案
您在模型中的关联是正确的。
要使用控制台将它们加入数据库,您可以执行以下操作:
ServiceProfile.create(service: Service.first, profile: Profile.first)
或者
profile = Profile.first
profile.service_profiles.create(service: Service.first)
推荐阅读
- php - get_post_meta 没有在 Wordpress functions.php 中打印/公开分配的自定义字段
- azure-functions - 如何使用函数应用程序复制 blob 数据并将其存储在子目录中
- java - 无法使用 Firebase ML Kit 读取更多 30 个字符的条形码
- android - Android 10 中尚未连接 Google Api 客户端,
- python - Debian软件包从Git安装依赖关系?
- json - Material UI Textfield 不对复杂字符串进行换行
- java - Spring在组件扫描中考虑了哪些包
- sharepoint-online - 我想禁用编辑表单字段,它包括人员选择器
- python - Flask 应用程序 ImportError:尝试在没有已知父包的情况下进行相对导入
- python - 如何在 Python 中有效地遍历选定的 Excel 工作表并将它们附加到数据框中?