Ruby on rails 如何将一个模型多次连接到另一个模型?
我有一个非常具体的问题,所以我会把它翻译成更容易理解和清楚的例子 所以我们有“国家”和“形象”模式。一个国家有旗有臂 这意味着我们必须将国家与图像连接两次。我尝试转换Rails指南的“连接到自身”配方,但是,我总是遇到一个例外:“预期图像,获得字符串”Ruby on rails 如何将一个模型多次连接到另一个模型?,ruby-on-rails,model-view-controller,Ruby On Rails,Model View Controller,我有一个非常具体的问题,所以我会把它翻译成更容易理解和清楚的例子 所以我们有“国家”和“形象”模式。一个国家有旗有臂 这意味着我们必须将国家与图像连接两次。我尝试转换Rails指南的“连接到自身”配方,但是,我总是遇到一个例外:“预期图像,获得字符串” *国家/地区模型 类别国家
*国家/地区模型
类别国家<申请记录
有一个:标志,类名:'Image',外键:'id'
有一个:arm,类名:'Image',外键:'id'
结束
*图像模型
类映像<应用程序记录
属于:国旗,阶级名称:“国家”
属于:arm,类别名称:“国家”
结束
您在图像
模型中没有任何东西可以指定图像是旗帜还是手臂
因此,添加一列表示
,它可以是“旗帜”或“武器”,并确保图像具有国家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
类映像{where表示:'flag'},类名:'Image'
有一个:arms,->{where表示:'arms'},类名:'Image'
结束
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