2015-04-23 65 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