Self join in active record association

7
Active Record Association Self-Join Ror lab. - Speicial episode - August 1st, 2013 Hyoseong Choi

description

Review of Self Join

Transcript of Self join in active record association

Page 1: Self join in active record association

Active Record AssociationSelf-Join

Ror lab.- Speicial episode -

August 1st, 2013

Hyoseong Choi

Page 2: Self join in active record association

User Model

class User < ActiveRecord::Base

has_and_belongs_to_many :friends, class_name: 'User', foreign_key: 'friend_id', association_foreign_key: 'user_id', join_table: 'users_friends'

def is_friend_of?(user_id) friend_ids.include? user_id end

end

Page 3: Self join in active record association

‘users’ table

$ rails g model User name$ rake db:migrate== CreateUsers: migrating ===============================-- create_table(:users) -> 0.0062s== CreateUsers: migrated (0.0062s) ======================

Page 4: Self join in active record association

‘users_friends’ table

$ rake db:migrate== CreateJoinTable: migrating ===============================-- create_table(:users_friends) -> 0.0035s== CreateJoinTable: migrated (0.0035s) ======================

$ rails g migration create_join_table user:references friend:references

class CreateJoinTable < ActiveRecord::Migration def change create_table :users_friends do | t | t.references :user, index: true t.references :friend, index: true

t.timestamps end endend

$ rake db:migrate== CreateJoinTable: migrating ===============================-- create_table(:users_friends) -> 0.0035s== CreateJoinTable: migrated (0.0035s) ======================

Page 5: Self join in active record association

User Friend

UsersFriend

class User < ActiveRecord::Base has_and_belongs_to_many :friendsend

class Friend < ActiveRecord::Base has_and_belongs_to_many :usersend

class UsersFriend < ActiveRecord::Base belongs_to :user belongs_to :friendend

has_and_belongs_to_many

Page 6: Self join in active record association

User User

UsersFriend

class UsersFriend < ActiveRecord::Base belongs_to :user belongs_to :friendend

has_and_belongs_to_many

class User < ActiveRecord::Base has_and_belongs_to_many :friends, class_name: ‘User’, foreign_key: ‘friend_id’ association_foreign_key: ‘user_id’end

self join

����������

�������������

������������

Page 7: Self join in active record association

감사합니다.����������� ������������������