1
有類似地雷的一些問題,但不完全是我要找的軌道有很多的本身
Many-to-many relationship with the same model in rails?
我的情況是這樣的用戶有很多朋友。
class User
has_many connections
has_many friends, through: connections, class_name: 'User'
end
class Connection
belongs to :user
belongs to :friend, class_name: 'User'
end
這讓我很接近,我可以這樣做:
first = User.create
second = User.create
first.friends << second
first.friends # => [ second ]
我想是雙向的
first.friends << second
second.friends # => [ first ]
的問題是,「朋友」的查詢是連接查看用戶的user_id的連接,然後查找所有的friend_ids。由於沒有與「second」的user_id連接,「second」沒有連接。
我在想兩個解決方案。 1)創建第一個連接時,用user_id =「second」創建另一個連接。 2)重寫「朋友」方法來產生一個SQL查詢,將會發現它。
對此有何想法?謝謝。
對不起,我沒有時間爲一個完整的答案,但你會發現這個對你的情況有所幫助。 http://railscasts.com/episodes/163-self-referential-association – Harry