0
votes

I'm new to Ruby on Rails, and I have one problem with more advanced database queries. I'm using rails 4

I have a User model, each user has one location in location table.

Second table is user_friendships. There is fields user_id, friend_id, and friend id references user in user table. User has relationship with this table like this: each user has many friends and friendships.

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'

Now I would like to display all user friendships who have relationship with this user, but only those friendships where friend has updated their location in past 20 minutes.

So I tried

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)

or this

    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})

but I'm getting this error: wrong argument type Symbol (expected Module), but the problem is that I don't even know if that's right.

What I want to achieve is to find all user friendships, but only those friendships where friends have updated their location in past 20 minutes.

1

1 Answers

2
votes

You have something like a user has one location relationship too, right?

Getting a user's friends:

user.friends

Getting friends who have updated their location within the last 20 minutes:

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