Jesse Jesse - 1 month ago 7
Ruby Question

How to keep attributes from two different tables synchronized in RoR?

What I want is to be able to easily be able to find the team name associated with a membership without having to send another request to the database. My plan was to just add a team_name attribute to the Memberships table, but I can't think of a way to have this new attribute stay in sync with the name attribute in the Teams table. In other words, I want it to be the case that, if the owner of a team changes the team's name, then all memberships to that team will be updated (with the new team name) as well.

Here is what my setup looks like. I've fairly new to Rails.

/app/models/membership.rb

class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :team
end


/app/models/team.rb

class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :team
end


/app/db/schema.rb

ActiveRecord::Schema.define(version: 20161022002620) do

create_table "memberships", force: :cascade do |t|
t.integer "user_id"
t.integer "team_id"
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "teams", force: :cascade do |t|
t.string "name"
t.integer "user_id"
end
end


If there is a better way to achieve what I am asking, then please let me know as well.

Answer

With this relational data your membership doesn't need a team name attribute - it is already available through the team association.

Generally there's no reason to keep data 'in sync' in this way unless you're performing some sort of computation. You don't need to store a name attribute on Membership - you can just use the existing one in Team.

I have seen people add duplicate database columns because they don't know how to traverse through associations. But unless you're using some noSql system, this isn't the 'right way' to do it - there is an underlying SQL API (through ActiveRecord) that performs lookups very efficiently.


in response to your comment. Do this:

class Membership < ActiveRecord::Base
  def name
    team.name
  end
end
Comments