Active Record Association
Self-Join
Ror lab.
- Speicial episode -
August 1st, 2013
Hyoseong Choi
User Model
class User < ActiveRecord::Base
has_and_belongs_to_many :friends,
class_name: 'User',
foreign_key: 'friend_id',...
‘users’ table
$ rails g model User name
$ rake db:migrate
== CreateUsers: migrating ===============================
-- cre...
‘users_friends’ table
$ rails g migration create_join_table user:references
friend:references
class CreateJoinTable < Acti...
User Friend
UsersFriend
class User < ActiveRecord::Base
has_and_belongs_to_many :friends
end
class Friend < ActiveRecord::...
User User
UsersFriend
class UsersFriend < ActiveRecord::Base
belongs_to :user
belongs_to :friend
end
has_and_belongs_to_ma...
감사합니다.
Upcoming SlideShare
Loading in …5
×

Self join in active record association

3,375 views

Published on

Review of Self Join

Published in: Education, Technology, Sports

Self join in active record association

  1. 1. Active Record Association Self-Join Ror lab. - Speicial episode - August 1st, 2013 Hyoseong Choi
  2. 2. 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
  3. 3. ‘users’ table $ rails g model User name $ rake db:migrate == CreateUsers: migrating =============================== -- create_table(:users) -> 0.0062s == CreateUsers: migrated (0.0062s) ======================
  4. 4. ‘users_friends’ table $ 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 end end $ rake db:migrate == CreateJoinTable: migrating =============================== -- create_table(:users_friends) -> 0.0035s == CreateJoinTable: migrated (0.0035s) ======================
  5. 5. User Friend UsersFriend class User < ActiveRecord::Base has_and_belongs_to_many :friends end class Friend < ActiveRecord::Base has_and_belongs_to_many :users end class UsersFriend < ActiveRecord::Base belongs_to :user belongs_to :friend end has_and_belongs_to_many
  6. 6. User User UsersFriend class UsersFriend < ActiveRecord::Base belongs_to :user belongs_to :friend end 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
  7. 7. 감사합니다.

×