我有一个特定的问题,所以我将其翻译成更易于理解和清晰的例子。
所以我们有"国家"one_answers"图像"模型。一个国家有其旗帜和手臂。
这意味着我们必须将国家连接到图像2次。我尝试改造Rails Guide的食谱"连接到自身",但是,我总是有一个例外:"图像预期,获得字符串"。
*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
您在Image
模型中没有任何内容来指定图像是标志还是ARM。
因此,添加一个可以为"标志"或"武器"的列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