2013-02-15 61 views
0

我試圖讓用戶通過電子郵件地址搜索自己的朋友。我想要做的事情如下:Rails搜索自引用關係

current_user.search('[email protected]') 

並讓它返回具有該電子郵件地址的當前用戶朋友的數組。

所以我有一個非常基本的友好關係建立在我的用戶模型

user.rb 
has_many :friendships 
has_many :friends, through: :friendships, source: :friend 
has_many :inverse_friendships, class_name: 'Friendship', foreign_key: 'friend_id' 
has_many :inverse_friends, through: :inverse_friendships, source: :user 

friendship.rb 
belongs_to :friend, class_name: 'User', foreign_key: 'friend_id' 
belongs_to :user 

我要建立在我的用戶模型的方法,可以通過電子郵件地址,通過他們的朋友進行搜索。它不工作這麼好

def search(query) 
    conditions = ['friends.user_id = ? AND email LIKE ? ', self.id, "%#{query}%"] 
    User.includes(:friends).where(conditions) 
end 

我想我只是不知道如何在這裏格式化我的活動記錄查詢/ SQL,因爲我想在一個自我指涉模型的關係進行搜索。有人有主意嗎?

謝謝!

回答

1

數字蛋糕正朝着正確的方向發展,但不完全正確。範圍是用戶的一種方法,而不是用戶。你需要的是:

def followers_by_email(email) 
    friends.where("email like ?", "%#{email}%") 
end 

這會返回一個ActiveRecord ::關係,你可以鏈中的其他條件,順序,分頁等作爲

user.followers_by_email("[email protected]").order(:first_name).limit(10) 
+0

這完全工作,顯然它應該。我試過這個,一定有某種類型或者我沒有注意到的東西,因爲當我再次嘗試時,它完美無缺地工作。 – goddamnyouryan 2013-02-17 22:16:27

+0

是的,我在上面的單詞中還有一個錯字。 – goddamnyouryan 2013-03-16 00:40:53

0

我似乎有一些成功:

conditions = ['contacts.user_id = ? AND users.email LIKE ? ', self.id, "%#{query}%"] 
User.includes(:inverse_friends).where(conditions) 

ŧ儘管這很奇怪,但我不完全確定它爲什麼會這樣。