问题
Using join tables in rails always casuses problems for me especially with having to create duplicate entries when reciprocration is assumed. I.e. i add someone as a friend and i automatically become theirs == two joins required.
Take a simple receipts app that keeps track between two people, who spent what.
A USER can have multiple FRIENDS. For each FRIEND they can track multiple TABS ( i.e. a tab for groceries, another for bills etc) each with multiple RECEIPTS added by either USER.
So in this case Ill need a FRIENDSHIP table and Ill need to create two friendships if i assume when one user declares another as a friend, the gesture is reciprocated. Here lies my problem. I need to link the shared TAB to both FRIENDSHIPS. This is basically saying
a friendship has many tabs and a tab has many friendships.
This involves another joins table... am i right?
It just seems like lots of duplication and im wondering if theres a better way to do this or how do you sanely handle this in your code? Do you create lots of callbacks to ensure when something is done to one friendship, its repeated for the other one too?
回答1:
Here is a plausible approach, if not the best one:
http://www.dweebd.com/sql/modeling-bidirectional-graph-edges-in-rails/
回答2:
I might be wrong ... correct me if i am wrong , just started rails
User
has_many :friend , :through => friendship
has_many :tab , :through => friend
Friendship
belong_to :user
belong_to :friend , :foreign_key => "user_id" , class_name => "User"
来源:https://stackoverflow.com/questions/4275567/how-do-you-handle-side-effect-of-duplication-when-using-joins-tables-i-e-reci