【问题标题】:Given a Rails 5 has_and_belongs_to_many, how to create a join record?给定 Rails 5 has_and_belongs_to_many,如何创建连接记录?
【发布时间】:2018-01-12 10:35:26
【问题描述】:

我有以下架构:

class Industry << ApplicationRecord
  has_and_belongs_to_many :departments
end

# Relationship table: departments_industries

class Department << ApplicationRecord
  has_and_belongs_to_many :industries
  has_and_belongs_to_many :job_titles
end

# Relationship table: departments_job_titles

class JobTitle << ApplicationRecord
  has_and_belongs_to_many :departments
end

当我要创建关系记录时:

department.job_titles.find_or_create_by(title: title)

只有当上面的查询创建的记录时,以上才会最终在departments_job_titles 中创建记录...如果 JobTitle 已经存在,Rails 不会在 departments_job_titles 中创建关系记录。

如何更新:

department.job_titles.find_or_create_by(title: title)

在找到或创建 JobTitle 记录时始终在 departments_job_titles 中创建关系记录?

【问题讨论】:

  • 在 Rails 风格指南 (github.com/bbatsov/rails-style-guide#activerecord ctrl+F "has_and_belongs_to_many") 中,建议使用 has_many :things, through: :join_records 而不是 HABTM,因为它(引用)"允许在连接模型”(如favoriteposition 属性等)

标签: ruby-on-rails ruby activerecord ruby-on-rails-5 activemodel


【解决方案1】:

试试这个:

department.job_titles << JobTitle.find_or_create_by(title: title)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    相关资源
    最近更新 更多