0

Suppose I have a User model, and I'd like to allow each user to choose their "top friends" that are also users, in order of favoriteness. This way a user can have a "best friend" and a "3rd best friend" and so on. I think what I'm looking for (correct me if this is a bad path to go down) is a habtm within the User model, with the added dimension of an order to them.

The end goal is to allow me to do something like:

@user.favorite_users => an ordered list of their favorite users.

@user.favorite_users.each do |user| //iterate through each user in order from best friend to worst friend end

I'm using Ruby 2.3.0, Rails 4.2.

Grant Nelson
  • 27
  • 1
  • 6
  • You might be interested in the Acts As List gem (https://github.com/swanandp/acts_as_list). Allows for easy implementation. I haven't used this for a many-to-many relationship, but I'd imagine you'd be best using a `has_many through` relationship and attaching `position` here. Hope that helps! – SRack Feb 24 '16 at 18:57
  • you need to use `has_many though:` not habtm as it does not allow you store additional data on the join table. Adding the "favoriteness" to the join table is trivial but setting up a many to many to the same table is quite difficult. http://stackoverflow.com/questions/2168442/many-to-many-relationship-with-the-same-model-in-rails – max Feb 24 '16 at 19:20

1 Answers1

1

Try the following:

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, -> { order 'friendships.order ASC'}, through: :friendships
end

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, class_name: 'User'  
end  

@user.friends will give you list of users ordered by order in friendships

Dharam Gollapudi
  • 6,328
  • 2
  • 34
  • 42
  • This is simple and effective - then friendships table has order:integer friend_id:integer user_id:integer, and indexes on user_id and friend_id. The order can be easily noted and changed using user.friendships.(...) It's working for me. – Grant Nelson Feb 25 '16 at 06:52