首页 > 解决方案 > 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 

标签: ruby-on-rails

解决方案


您在模型中的关联是正确的。

要使用控制台将它们加入数据库,您可以执行以下操作:

ServiceProfile.create(service: Service.first, profile: Profile.first)

或者

profile = Profile.first 
profile.service_profiles.create(service: Service.first)

推荐阅读