Created
November 25, 2014 20:54
-
-
Save bjjb/f64222da389ebb4d097a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example of using | |
require 'sqlite3' | |
require 'active_record' | |
ActiveRecord::Base.establish_connection("sqlite3::memory:") | |
conn = ActiveRecord::Base.connection | |
conn.create_table :users do |t| | |
t.string :name | |
end | |
conn.create_table :user_matches do |t| | |
t.references :sender | |
t.references :target | |
def to_s; "#{sender}->#{target}"; end | |
end | |
class UserMatch < ActiveRecord::Base | |
belongs_to :target, class_name: 'User' | |
belongs_to :sender, class_name: 'User' | |
end | |
class User < ActiveRecord::Base | |
has_many :incoming_user_matches, class_name: 'UserMatch', foreign_key: :target_id | |
has_many :outgoing_user_matches, class_name: 'UserMatch', foreign_key: :sender_id | |
has_many :senders, through: :incoming_user_matches | |
has_many :targets, through: :outgoing_user_matches | |
def to_s; name; end | |
end | |
alice = User.create(name: 'Alice') | |
bob = User.create(name: 'Bob') | |
cecil = User.create(name: 'Cecil') | |
bob.targets << alice | |
alice.targets << cecil | |
cecil.targets << bob | |
UserMatch.all.each { |um| puts "User Match: #{um}" } | |
User.all.each do |u| | |
puts "#{u} is targeting: #{u.targets.map(&:to_s).join(',')}" | |
puts "#{u} is targeted by: #{u.senders.map(&:to_s).join(',')}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment