如何将一个模型连接到另一个模型多次?

Ale*_*org 2 model-view-controller ruby-on-rails

我有一个特定的问题所以我会把它翻译成更容易理解和清晰的例子.

所以我们有'Country'和'Image'模型.一个国家有它的旗帜和它的手臂.

这意味着我们必须将Country to Image连接2次.我尝试转换Rails指南的配方'连接到自己',然而,我总是得到一个例外:"图像预期,得到字符串".

*Country model
   class Country < ApplicationRecord
     has_one :flag, class_name: 'Image', foreign_key: 'id'
     has_one :arm,  class_name: 'Image', foreign_key: 'id'
   end

*Image model
   class Image < ApplicationRecord
     belongs_to :flag, class_name: 'Country'
     belongs_to :arm, class_name: 'Country'
   end
Run Code Online (Sandbox Code Playgroud)

Ste*_*zyn 6

Image模型中没有任何内容可指定图像是标志还是手臂.

因此,添加一个represents可以是"flag"或"arms" 的列,并确保该图像具有country_id整数字段,然后将关系设置为...

 class Image < ApplicationRecord
   belongs_to :country
 end

 class Country < ApplicationRecord
   has_one :flag, -> {where represents: 'flag'}, class_name: 'Image'
   has_one :arms, -> {where represents: 'arms'}, class_name: 'Image'
end
Run Code Online (Sandbox Code Playgroud)