我正在實施系統,使用戶能夠遵循「可跟蹤」(在我的情況下,這些可能是一個事件,地點或其他用戶)。許多與多態關聯不能在兩個方向工作
我的想法:
關注模型認爲user_ID的,隨動型和followale_id(連接表)
class Follow < ActiveRecord::Base
belongs_to :user
belongs_to :followable, polymorphic: true
end
事件
class Event < ActiveRecord::Base
has_many :follows, as: :followable
has_many :users, through: :follows
end
廣場
class Place < ActiveRecord::Base
has_many :follows, as: :followable
has_many :users, through: :follows
end
用戶
class User < ActiveRecord::Base
has_many :follows
has_many :events, through: :follows, source: :followable, source_type: "Event"
has_many :places, through: :follows, source: :followable, source_type: "Place"
has_many :users, through: :follows, source: :followable, source_type: "User"
end
的問題是,維吾爾只能在一個方向,我可以這樣做:
user.follows.create(followable:event1) #follow event1
user.follows.create(followable:place1) #follow place1
user.follows.create(followable:user1) #follow user1
user.follows # displays all following relations user has established
但是,我不能這樣做:
event1.follows #return follow objects(some user - event1 pairs)
event1.users #return all of the users that follow this event
user1.users #return all of the users that user1 follows, the most confusing part..
所有上述返回零。
我應該如何建立關係,使其在兩個方向上工作?
另外,我想聽聽一些關於如何改善這個想法的評論,這是我第一次玩更復雜的實時信息。 預先感謝您。
快速思考:你確定你沒有看到'event1.follows'的陳舊緩存嗎?當你嘗試'event1.follows(true)'時會發生什麼? (這裏的'true'告訴ActiveRecord重新加載關聯,而不是使用它的緩存,如果有的話) –
輸出:# –
Wojciech
event1.follows.to_sql怎麼樣? –