Hi if i have one model say with objects for each letter of the alphabet
e.g a,b,c ... x,y,z and i want to allow users to create there own
favourite pairings of these e.g.
ab, cd, ef, gp and allow them to discuss via comments on each pairing,
whats teh best way to model this in rails?
Use a Pairing class with a polymorphic association.
the order of teh letters DOESNT matter so ab IS the SAME as ba. Id
rather avoid duplication in my "Pairings" table because that would mean
id have to assign user commments to both ab and ba.
Sort the object IDs in some unambiguous way before creating a pairing.
So if i sort them by their name then id, and I have A and B with ids 1
and 2 respectively then in my pairing controller id do
@pairing = Pairing.new(params[:pairing])
@pairing.save (Which would use the callback before_create above)
So A has an Ingredient_Partner B
i.e. A.alphabet_partners ===> B
That's right.
But would it work the other way i.e.
B.alphabet_partners ==> A ???
i thought it wouldnt without creating a 2nd pairing with the letters
switched.
Look at the code I gave you, and think about how it would behave.
Better yet, write some tests and try it! Ask the computer, not me.
Thanks again.
Ok i know why your saying to have a consistent sorting method, its so as
to avoid a duplicate situation i.e. if i always sort by the letter and
id then i will always save as ab and not ba. If theres already an ab
there and i have some validations i can avoid reading in another ab.
That bit i understand.
But the problem is i will only have, and ive tested this, a one way
relationship. That is 'A' is an "alphabet" which has an
"alphabet_partner" of 'b'.
I.e. a.alphabet_partner = b.
But that's the problem, 'B' is just an "alphabet_partner" in this
pairing table. There is nothing in the pairing table nor the
associations currently set that say b
"B" is ALSO an "alphabet" which has an "alphabet_partner" of 'A'.
i.e. b.alpahbet_partner == . it will NOT yield 'A'
I have tried this with my setup and thats the result i get but also
thinking about it makes me believe this can only be the end result.
I read up and i think (im not sure though) but i think i need something
called bidirectional relationship. The only problem is I dont know how
to implement this.
Are you sure my results should be any different?
Hi again, thanks so much for your help i really appreciate it. I wanted
to write another association like you said before but there is no
Alphabet_Partner class to write it in. Its just a self reference to
Alphabet table.
[...]
You don't need an AlphabetPartner class. You just need a second
association between Alphabet and Pairing on the alphabet_partner_id
column. See the docs or the associations guide for how to do this.