Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## migrations
- class CreateUsers < ActiveRecord::Migration
- def self.up
- create_table :users do |t|
- t.string :name
- t.timestamps
- end
- end
- def self.down
- drop_table :users
- end
- end
- ##
- class CreateKonnections < ActiveRecord::Migration
- def self.up
- create_table :konnections do |t|
- t.integer :first_user_id
- t.integer :second_user_id
- t.timestamps
- end
- # join table
- create_table :konnections_users, :id => false do |t|
- t.integer :konnection_id
- t.integer :user_id
- end
- end
- def self.down
- drop_table :konnections
- drop_table :konnections_users
- end
- end
- ## User
- class User < ActiveRecord::Base
- has_and_belongs_to_many :konnections, :join_table => :konnections_users
- def create_konnection(user_to_connect)
- transaction do
- konnection = Konnection.create(:first_user => self, :second_user => user_to_connect)
- self.konnections << konnection
- user_to_connect.konnections << konnection
- end
- end
- end
- ## Konnection
- class Konnection < ActiveRecord::Base
- belongs_to :first_user, :class_name => 'User'
- belongs_to :second_user, :class_name => 'User'
- def user
- # self.user_id returns a string! we need to convert it to an id before we can compare id:s
- self.user_id.to_i == self.first_user_id ? self.second_user : self.first_user
- end
- end
- ## console
- # >> User.first.name
- # => "Allan"
- # >> User.last.name
- # => "Lucy"
- # >> User.first.create_konnection(User.last)
- # => [#<Konnection id: 1, first_user_id: 1, second_user_id: 2, created_at: "2008-10-31 20:20:41", updated_at: "2008-10-31 20:20:41">]
- # >> User.first.konnections.first.user.name
- # => "Lucy"
- # >> User.last.konnections.first.user.name
- # => "Allan"
- # >>
Add Comment
Please, Sign In to add comment