【问题标题】:In Rails, How should I allow users to create an ordered list of other users?在 Rails 中,我应该如何允许用户创建其他用户的有序列表?
【发布时间】:2016-02-24 18:50:35
【问题描述】:

假设我有一个 User 模型,我想让每个用户按照喜爱的顺序选择他们的“顶级朋友”,他们也是用户。这样一个用户可以有一个“最好的朋友”和“第三个最好的朋友”等等。我认为我正在寻找的(如果这是一条不好的路径,请纠正我)是用户模型中的一个习惯,并为它们增加了订单维度。

最终目标是允许我做类似的事情:

@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。

【问题讨论】:

  • 您可能对 Acts As List gem (github.com/swanandp/acts_as_list) 感兴趣。便于实施。我没有将它用于多对多关系,但我想你最好使用has_many through 关系并在此处附加position。希望有帮助!
  • 您需要使用has_many though: 而不是 habtm,因为它不允许您在连接表上存储其他数据。将“收藏夹”添加到连接表是微不足道的,但在同一个表中设置多对多是相当困难的。 stackoverflow.com/questions/2168442/…

标签: ruby-on-rails associations rails-activerecord


【解决方案1】:

尝试以下方法:

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 将为您提供orderfriendships 中排序的用户列表

【讨论】:

  • 这个简单而有效——然后friendships表有order:integerfriend_id:integer user_id:integer,以及user_id和friend_id上的索引。使用 user.friendships 可以轻松记录和更改顺序。(...) 它对我有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多