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!

Answers


You can order on the associated table by doing a nested join, like so:

@posts = Post.joins(:user => :friendships).order("friendships.friended_at")

Need Your Help

Cannot get email script working

php email

Here is the code I have in contact.php:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.