2017-05-31 64 views
-1

我正在將一個複雜的PostgreSQL字符串翻譯成Arel,並且想知道「arelize」has_and_belongs_to_many表的正確方法是什麼。例如,下面是相關機型:將has_and_belongs_to_many錶轉換爲Arel的正確方法是什麼?

class Release < ApplicationRecord 
    has_and_belongs_to_many :vulnerabilities 
end 

class Vulnerability < ApplicationRecord 
    has_and_belongs_to_many :releases 
end 

類別設置創建一個表中調用releases_vulnerabilities,但我似乎無法將其轉換爲阿雷爾。我試過在我的滑軌控制檯Release_Vulnerability.arel_table,然後我嘗試Arel::Table.new(:releases_vulnerabilities),但第二個實現不允許我查詢關聯的外鍵。將此錶轉換爲arel的正確方法是什麼?

+1

爲什麼不使用'has_many:releases,through:assembly_parts'?有沒有真正的理由不創建AssemblyPart模型?這可以讓你輕鬆地將所有東西變成arel。另外,爲什麼你認爲在這種情況下你需要艾爾? – radha

+0

「第二個實現不允許我查詢關聯的外鍵」是什麼意思? – chumakoff

+0

爲什麼你想首先將它「分解」呢? Arel是一個非常不穩定的私人api,它在Rails升級時無需通知就更改。 – Iceman

回答

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,仍然有效更新代碼,如果你看兩個查詢,你會在兩種情況下看到它的聯接。 現在關於「arielize」的想法看看this conversion I did

相關問題