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

时间:2016-12-09 10:20:05

标签: ruby-on-rails model-view-controller

我有一个非常具体的问题,所以我会把它翻译成更易懂和清晰的例子。

所以我们有'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

1 个答案:

答案 0 :(得分:6)

Image模型中没有任何内容可指定图像是旗帜还是手臂。

因此,添加一个可以是“flag”或“arms”的列represents,并确保图像具有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
相关问题