【问题标题】:Has_many of different models association in RailsHas_many 在 Rails 中的不同模型关联
【发布时间】:2018-03-12 05:49:19
【问题描述】:

我有几个不同的模型,我想添加多个图像。

我有一个图像模型,其中 belongs_to 关联设置到不同的拥有模型(每个拥有模型都定义了 has_many :images)。

我想知道我应该创建什么适当的迁移,以便为每个拥有的模型添加一个 image_ids 列。

我假设是这样的......

rails g migration AddImagesToBusinesses images businesses image_ids:integer

但是,我很困惑,因为我认为您只能通过这种方式建立一个关联,并且需要通过在 images 表中添加一列来识别它所属的模型的 id 来完成它(这里有几种不同的型号)。

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails activerecord associations rails-migrations


    【解决方案1】:

    当您关注图像与其他模型的关系时。你应该试试这样的多态关联。

    生成图像模型:

    class CreateImages < ActiveRecord::Migration
      def change
        create_table :images do |t|
          t.string :file_id
          t.boolean :featured
          t.references :imageable, polymorphic: true, index: true
          t.timestamps null: false
        end
      end
    end
    

    更新图像模型:

    class Image < ActiveRecord::Base
      attachment :file
      belongs_to :imageable, polymorphic: true
    end
    

    像这样添加与其他模型的关联

    class Model < ActiveRecord::Base
      has_many :images, as: :imageable, dependent: :destroy
      accepts_attachments_for :images, attachment: :file
    end
    

    更多详情请Ruby on Rails Guide

    【讨论】:

    • 好的,谢谢!我看过这些,但不确定它们是否适用于这里。
    【解决方案2】:

    我认为您需要多态关联。 请在此处查看documentaions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 2017-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多