Search code examples
ruby-on-railsactiverecordassociationsrails-migrations

Has_many of different models association in Rails


I have a few different models which I would like to add multiple images to.

I have an image model with belongs_to associations set up to the different owning models (each of these owning models has has_many :images defined).

I would like to know what's the appropriate migration I should create in order to add an image_ids column to each of owning models.

I assume something like this...

rails g migration AddImagesToBusinesses images businesses image_ids:integer

However, I'm confused as I believe that you can only make one association this way and it would need to be completed by adding a column to the images table to identify the id of the model it belongs to (here there are a few different models).

Thank you for your help.


Solution

  • As you concern about relationship of image to other model. You should try polymorphic associations like this.

    Generate the Image model:

    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
    

    Update the Image model:

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

    Add association to other models like this

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

    For more details you Ruby on Rails Guide.