Guest User

Untitled

a guest
May 25th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. ## migrations
  2. class CreateUsers < ActiveRecord::Migration
  3. def self.up
  4. create_table :users do |t|
  5. t.string :name
  6. t.timestamps
  7. end
  8. end
  9.  
  10. def self.down
  11. drop_table :users
  12. end
  13. end
  14. ##
  15. class CreateKonnections < ActiveRecord::Migration
  16. def self.up
  17. create_table :konnections do |t|
  18. t.integer :first_user_id
  19. t.integer :second_user_id
  20. t.timestamps
  21. end
  22.  
  23. # join table
  24. create_table :konnections_users, :id => false do |t|
  25. t.integer :konnection_id
  26. t.integer :user_id
  27. end
  28.  
  29. end
  30.  
  31. def self.down
  32. drop_table :konnections
  33. drop_table :konnections_users
  34. end
  35. end
  36.  
  37.  
  38. ## User
  39. class User < ActiveRecord::Base
  40. has_and_belongs_to_many :konnections, :join_table => :konnections_users
  41.  
  42. def create_konnection(user_to_connect)
  43. transaction do
  44. konnection = Konnection.create(:first_user => self, :second_user => user_to_connect)
  45. self.konnections << konnection
  46. user_to_connect.konnections << konnection
  47. end
  48. end
  49. end
  50.  
  51.  
  52. ## Konnection
  53. class Konnection < ActiveRecord::Base
  54. belongs_to :first_user, :class_name => 'User'
  55. belongs_to :second_user, :class_name => 'User'
  56.  
  57. def user
  58. # self.user_id returns a string! we need to convert it to an id before we can compare id:s
  59. self.user_id.to_i == self.first_user_id ? self.second_user : self.first_user
  60. end
  61. end
  62.  
  63. ## console
  64. # >> User.first.name
  65. # => "Allan"
  66. # >> User.last.name
  67. # => "Lucy"
  68. # >> User.first.create_konnection(User.last)
  69. # => [#<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">]
  70. # >> User.first.konnections.first.user.name
  71. # => "Lucy"
  72. # >> User.last.konnections.first.user.name
  73. # => "Allan"
  74. # >>
Add Comment
Please, Sign In to add comment