jeudi 12 janvier 2017

How to populate the ids in join table (has_and_belongs_to_many)?

I have a command model

class Command < ActiveRecord::Base
  attr_accessible :name, :command, :action, :reboot_action, :num_retries,   :timeout, :server_id
  has_and_belongs_to_many :servers
end

I have a Server model

class Server < ActiveRecord::Base
  has_and_belongs_to_many :commands
end

I have a join table which has command id and server id.

class CreateCommandsServersJoinTable < ActiveRecord::Migration
  def up
    create_table :commands_servers, :id => false do |t|
      t.references :command
      t.references :server
    end
    add_index :commands_servers, [:command_id, :server_id]
  end

  def down
    drop_table :commands_servers
  end
end

Is there a way to populate commands_servers table with command id and server id when the command is created?

Aucun commentaire:

Enregistrer un commentaire