将has_and_belongs_to_many表转换为Arel的正确方法是什么?

时间:2017-05-31 15:24:19

标签: ruby-on-rails postgresql activerecord

我正在将一个复杂的PostgreSQL字符串翻译成Arel,并且想知道正确的方法是什么?#isgize'一个has_and_belongs_to_many表。例如,以下是相关模型:

class Release < ApplicationRecord
  has_and_belongs_to_many :vulnerabilities
end

class Vulnerability < ApplicationRecord
  has_and_belongs_to_many :releases
end

类设置会创建一个名为releases_vulnerabilities的表,但我似乎无法将其转换为arel。我已经在我的rails控制台Release_Vulnerability.arel_table中尝试了然后我尝试了Arel::Table.new(:releases_vulnerabilities),但第二个实现并不允许我查询相关的外键。将此表转换为arel的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

你可以完美地改变这个

class Release < ApplicationRecord
  has_and_belongs_to_many :vulnerabilities
end

class Vulnerability < ApplicationRecord
  has_and_belongs_to_many :releases
end

进入这个

class Release < ApplicationRecord
  has_many :vulnerabilities
  has_many :vulnerabilities, through: :release_vulnerabilities
end

class ReleaseVulnerabilities < ApplicationRecord
  belongs_to :vulnerability
  belongs_to :release
end

class Vulnerability < ApplicationRecord
  has_many :release_vulnerabilities
  has_many :releases, through: :release_vulnerabilities
end

你不会失去任何关系,你甚至不需要更新代码,因为@ vulnerability.releases仍然有效,如果你看两个查询,你会在两种情况下都看到它的连接。 现在关于&#34; arielize&#34;的想法看看this conversion I did