Search code examples
ruby-on-railsdatabasemodels

Rails - adding new record to all Models at once


Lets say I have a Model called Building and another Model called Issue.

Issue belongs_to Building

Building has_many Issues

I have multiple Buildings, with many Issues. Right now, I have to add each Issue to each Building one at a time.

How can I add one Issue to all Buildings at the same time?


Solution

  • Seems you need a has_and_belongs_to_many relationship in both models. And create a table for that:

    rails g migration create_buildings_issues building_id:integer issue_id:integer
    

    Edit migration to remove auto index and add compound index:

    create_table :buildings_issues, index: false do |t|
      t.references :building
      t.references :issue
    end
    add_index :buildings_issues, [:building_id, :issue_id]
    

    Then create this table in DB:

    rake db:migrate
    

    Then you could add issue to multiple buildings:

    any_issue.buildings << Building.all
    

    Or add issues to any building:

    any_building.issues << heat_issue