[英]Rails: Using custom column to look up for has_many association
我有3個模型:用戶,列表,關注
我正在嘗試實施一個系統,
這是我嘗試構建此系統的方法:
首先,我們有一個列表數據庫表:
lists: id, user_id
並指定如下模型:
class User < ActiveRecord::Base
has_many :lists
end
class List < ActiveRecord::Base
belongs_to :user
end
我們可以做User.first.lists
沒有問題。
現在,當我嘗試建立追隨者時,我面臨的挑戰就來了。 我希望用戶能夠找到
這是我要用來實現上述功能的數據庫表:
followings: user_id, list_id, list_user_id
在此表定義中, user_id
指定誰跟隨列表, list_id
指定要跟隨的列表, list_user_id
指定要跟隨的列表的所有者。 這里使用list_user_id
來加速數據庫查找,因此我們不必將lists
表與users
表list_user_id
在一起。
現在我被卡住了。 我試圖將用戶模型更改為以下內容:
class User < ActiveRecord::Base
has_many :lists
has_many :followings
# Works
has_many :following_lists, :through => :followings, :class_name => "List", :source => :list
# Doesn't work
has_many :followed_lists, :through => :followings, :class_name => "List", :source => :list, :conditions => {:list_user_id => self.id}
# Doesn't work
has_many :followers, :through => :followings, :class_name => "User", :source => :user
end
通過has_many :following_lists
毫無問題地完成了第一個目標“查找他關注的所有列表”。 但是,似乎很難獲得用戶的“所有關注列表”和“所有關注者”。
問題在於,似乎無法followings
表中指定用於查找的鍵。 例如,當尋找用戶A的追隨者時,我需要在followings
表中list_user_id
等於A.id
所有行,但是has_many
方法沒有提供執行此操作的選項,也沒有條件:conditions => {:list_user_id => self.id}
工作(它會抱怨undefined method 'id'
)。
所以..您將如何處理這種情況? 有沒有更好的方法來設計表,還是我們可以根據當前表的定義實際制定出一些東西?
順便說一句, Following
是定義Following
模型的方式:
class Following < ActiveRecord::Base
attr_accessible :list_id, :list_user_id, :user_id
belongs_to :user
belongs_to :list
belongs_to :list_user, :class_name => "User"
end
您正在嘗試獲得以下兩點:
1.)他遵循的所有列表
2.)跟隨他的列表的所有用戶(或等效地,所有“關注者”)
這兩個過濾器都位於用戶擁有的列表的頂部。 因此,與:through => followings的關聯是不正確的。 既然這樣,列表的范圍就僅限於您關注的列表,而不是您擁有的列表。
一種想要的方法是這樣的:
def followed_lists
# This essentially limits your owned lists to ones with an entry in the followings table
lists.join(:followings).all
end
def users_following_owned_lists
lists.followers.all
end
您需要將關注者關聯添加到列表AR。
class List < ActiveRecord::Base
has_many :followings
has_many :followers, :through => :followings, :class_name => "User", :source => :user
end
還要注意,follows表上的list_user_id並不是真正需要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.