Created
February 26, 2012 02:38
-
-
Save bokmann/1912350 to your computer and use it in GitHub Desktop.
Another example for Mel...
This file contains 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
# Mel, Here is another gist for you, perhaps slightly better than the last. | |
# First, the migrations are exactly the same, but this improves the left-right | |
# situation slightly. | |
# kit.rb | |
class Kit < ActiveRecord::Base | |
has_many :peer_kit_relations, | |
:class_name => "KitRelation", | |
:foreign_key => :left_kit_id | |
has_many :peer_kits, | |
:through => :peer_kit_relations, | |
:source => :right_kit | |
def associate_kit(other_kit) | |
peer_kits << other_kit | |
other_kit.peer_kits << self | |
end | |
end | |
# kit_relation.rb | |
class KitRelation < ActiveRecord::Base | |
belongs_to :left_kit, :class_name => "Kit" | |
belongs_to :right_kit, :class_name => "Kit" | |
end | |
# exercising from rails console | |
k1 = Kit.create(:name => "First Kit") | |
k2 = Kit.create(:name => "Second Kit") | |
k3 = Kit.create(:name => "Third Kit") | |
# Note that this works: | |
k1.peer_kits << k2 | |
# but the problem is the relationship goes one way only - so while k2 | |
# is in k1's peer list, k1 is not in k2's peer list. This means every | |
# time you have to do this: | |
k1.peer_kits << k2 | |
k2.peer_kits << k1 | |
# To help with that, there is the associate_kit method: | |
k1.associate_kit(k2) | |
# I still consider that an ugly solution. | |
# There should be a way to push knowledge of this bi-directional | |
# 2-record creation into the peer_kit_relations, using something | |
# like a block passed to the relationship: | |
has_many :peer_kit_relations, | |
:class_name => "KitRelation", | |
:foreign_key => :left_kit_id do | |
# some kind of magic goes in this block | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ok, I lied - I wasn't too tired to try it. I'm posting the new code to the old gist over at https://gist.github.com/1912278