2015-04-23 67 views
0

我是Ruby on Rails的新手,我遇到了一個更高級的數據庫查詢問題。我正在使用rails 4高級rails 4數據庫查詢

我有一個用戶模型,每個用戶在位置表中有一個位置。

第二個表是user_friendships。用戶表中存在字段user_id,friend_id和用戶id參考用戶。用戶與此表有如下關係:每個用戶都有很多朋友和友誼。現在

class User 

    has_one :location, dependent: :destroy 
    has_many :user_friendships 
    has_many :friends, through: :user_friendships 

class user_friendship 

    belongs_to :user 
    belongs_to :friend, class_name: 'User', foreign_key: 'friend_id' 

我想顯示誰與該用戶關係的所有用戶的友誼,但只有其中的朋友已經在過去的20分鐘更新一次自己的位置之間的友誼。

所以,我想

time = params[:timestamp] 
endtime = time.to_i - 1200 
friends = UserFriendship.where(user_id: <user.id>) 
updted = friends.include(:users).include(:location).where(updated_at: time..endtime) 

或本

friends = UserFriendship.where(user_id: <user.id>) 
    updted = friends.include(:users).include(:location).where("created_at <= :start_date AND created_at >= :end_date", 
{start_date: time, end_date: endtime}) 

,但我得到這個錯誤:wrong argument type Symbol (expected Module),但問題是,我甚至不知道這是否是正確的。

我想要實現的是找到所有用戶的友誼,但只有那些朋友在過去20分鐘內更新了他們的位置的朋友。

回答

2

你也有類似user has one location的關係,對不對?

獲取用戶的朋友:

user.friends 

入門的朋友誰已經在過去的20分鐘內更新了自己的位置:

user. 
friends. 
joins(:locations). 
where("#{Location.table_name}.updated_at >= ?", 20.minutes.ago) 
+0

謝謝你的幫助,但你的回答給我看,我問我的問題不正確。對不起,我更新了我的問題。 我想知道的是如何找到user_friendships表中與過去20分鐘內更新其位置的朋友的所有用戶友誼。 – Santar