Rails sort entries based on attributes of related model
I have a strange scenario: I would like to order all posts P by the time at which P's creator and the current user became friends.
The result would be a list of posts with newer friends' posts at the top and older friends' posts at the bottom. We can assume all users are friends of all other users, but each friendship has varying creation times.
I have Post, User, and Friendship models. Posts belong to users and users have many friendships.
class User < ActiveRecord::Base has_many :friendships has_many :friends, :through => :friendships has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id" has_many :inverse_friends, :through => :inverse_friendships, :source => :user end class Friendship < ActiveRecord::Base belongs_to :user belongs_to :friend, :class_name => "User" end class Post < ActiveRecord::Base belongs_to :user end
What's the best way to do this? Thanks!
You can order on the associated table by doing a nested join, like so:
@posts = Post.joins(:user => :friendships).order("friendships.friended_at")