我是Ruby on Rails的新手,对于更高级的数据库查询,我有一个问题。我使用的是rails 4
我有一个用户模型,每个用户在位置表中有一个位置。
第二个表是user_friendships。user表中有字段user_id、friend_id和好友id引用user。用户与这个表的关系是这样的:每个用户都有很多朋友和朋友。
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分钟内更新了他们的位置的友谊。
发布于 2015-04-24 17:24:35
你也有类似于user has one location的关系,对吧?
获取用户的好友:
user.friends获取在过去20分钟内更新位置的朋友:
user.
friends.
joins(:locations).
where("#{Location.table_name}.updated_at >= ?", 20.minutes.ago)https://stackoverflow.com/questions/29835334
复制相似问题