在 Rails 中,我应该如何允许用户创建其他用户的有序列表?
In Rails, How should I allow users to create an ordered list of other users?
假设我有一个用户模型,我想让每个用户按照喜好顺序选择他们的 "top friends" 也是用户。这样用户就可以拥有 "best friend" 和“第三好朋友”等等。我认为我正在寻找的(如果这是一条糟糕的下降路径,请纠正我)是用户模型中的一个 habtm,并为它们添加了订单维度。
最终目标是允许我做类似的事情:
@user.favorite_users
=> 他们最喜欢的用户的有序列表。
@user.favorite_users.each do |user|
//iterate through each user in order from best friend to worst friend
end
我正在使用 Ruby 2.3.0,Rails 4.2。
尝试以下操作:
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
将为您提供按 order
在 friendships
中排序的用户列表
假设我有一个用户模型,我想让每个用户按照喜好顺序选择他们的 "top friends" 也是用户。这样用户就可以拥有 "best friend" 和“第三好朋友”等等。我认为我正在寻找的(如果这是一条糟糕的下降路径,请纠正我)是用户模型中的一个 habtm,并为它们添加了订单维度。
最终目标是允许我做类似的事情:
@user.favorite_users
=> 他们最喜欢的用户的有序列表。
@user.favorite_users.each do |user|
//iterate through each user in order from best friend to worst friend
end
我正在使用 Ruby 2.3.0,Rails 4.2。
尝试以下操作:
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
将为您提供按 order
在 friendships