【问题标题】:How to connect one model to another more than once?如何将一个模型多次连接到另一个模型?
【发布时间】:2017-04-24 19:06:24
【问题描述】:

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

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

这意味着我们必须将 Country 与 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

【问题讨论】:

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


    【解决方案1】:

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

    所以,添加一个列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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 2023-03-19
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多