Mush
Mush

Reputation: 57

Rails: Making sure two tables are "sync'd"

Relationships:

When creating an Announcement, the user must assign a Roster to it (whose data will be used to create its new AnnouncementRoster).

My models:

class User < ActiveRecord::Base
  has_many :roster_players
  has_many :rosters, -> { uniq } ,  :through => :roster_players
  has_many :announcement_rosters, -> { uniq } ,  :through => :announcement_players
end

class Roster < ActiveRecord::Base
  has_many :roster_players
  has_many :users, -> { uniq }, through: :roster_players
end

class RosterPlayer < ActiveRecord::Base
  belongs_to :roster
  belongs_to :user
  validates :user_id, :uniqueness => { :scope => :roster_id }
end


class Announcement < ActiveRecord::Base
  has_one :announcement_roster
end

class AnnouncementRoster < ActiveRecord::Base
  has_many :announcement_players
  has_many :users, -> { uniq }, through: :announcement_players
end

class AnnouncementPlayer < ActiveRecord::Base
  belongs_to :announcement
  belongs_to :user
end

I believe I need different relationship models (RosterPlayer, AnnouncementPlayer, TaskPlayer, etc.) because different relationships require different attributes. For example: an AnnouncementPlayer has a read? column, TaskPlayer has a progress column, and RosterPlayer has a captain? column.

Question: What is the best way to make sure that the AnnouncementRoster is "sync'd" with the Roster it was copied from? In other words, if the copied Roster's data is changed (a user is added or removed from it) than the corresponding AnnouncementRoster should be updated accordingly.

Upvotes: 2

Views: 578

Answers (1)

New Alexandria
New Alexandria

Reputation: 7324

The strategies you want to decide between, are:

  1. use database-level idioms to cascade those updates (invisibly to rails)
  2. Use after_save and after_update, having Rails push the changes
  3. Create non-automatic methods (rake tasks) in Rails to push the updates on a cron
  4. Push the changes with SQL scripts living in bash and cron-controlled (or similarly, have the changes sent by pigeon)

Which of these you choose is really dependent on your environment, application metrics, resiliency, etc.

Sorry this is an overview answer. Someone else can probably talk through the pro-con sides of this and help you make that decision based on yet-unstated info.

Upvotes: 1

Related Questions