Skip to content

Instantly share code, notes, and snippets.

@chrisdpeters
Last active March 2, 2016 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisdpeters/e7ae0197218651b14571 to your computer and use it in GitHub Desktop.
Save chrisdpeters/e7ae0197218651b14571 to your computer and use it in GitHub Desktop.
Users, Contacts, and Friendships
class Contact < ActiveRecord::Base
has_many :users
has_many :friendships
end
# This links up a user's contacts
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :contact
end
class User < ActiveRecord::Base
belongs_to :contact # The user's own contact details
has_many :friendships # Joins up user's friends
has_many :friends, through: :friendships # Queries for user's friends
end
class UsersController < ApplicationController
def show
# This grabs both the user's contact details (:contact) and friends (:friends)
@user = User.includes(:contact, :friends).find(params[:key])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment