How to query to get all users based on a nested resource?
Given:
Room (id, updated_at)
RoomMember (room开发者_开发百科_id, user_id)
User (id)
In rails how can I get all users that belong to all rooms that were last updated_at in the past 24 hours?
Thanks
User.select('distinct users.*').joins(:rooms).where('rooms.updated_at > ?', 1.day.ago)
Assuming your models are as follows:
class User
has_many :room_members
has_many :rooms, :through => :room_members
end
class RoomMember
belongs_to :user
belongs_to :room
end
class Room
has_many :room_members
has_many :users, :through => :room_members
end
You can use the following:
User.all(:select => "DISTINCT users.*",
:joins => :rooms, :conditions => ["rooms.updated_at >=", 1.day.ago])
精彩评论