使用 has_many :through 创建有序列表

发布于 2024-11-02 14:35:18 字数 692 浏览 2 评论 0原文

我设置了一个 has_many :through 与连接模型上的位置列关联,这样我就可以保存练习列表。但现在我正在寻找与控制器中的这些对象交互的最佳方式。

我应该调用 Activity.drillsActivity.drill_list 来获取有序列表吗?

维持职位的最佳方法是什么?我是否必须手动更新 DrillList 中的所有位置?

class Drill < ActiveRecord::Base
  has_many :drill_list, :order => "position"
  has_many :activities, :through => :drill_list, :order => "position"
end

class DrillList < ActiveRecord::Base
  belongs_to :activity
  belongs_to :drill
end

class Activity < ActiveRecord::Base
  has_many :drill_list, :order => "position", :dependent => :destroy
  has_many :drills, :through => :drill_list, :order => "position"  
end

I set up a has_many :through association with a position column on the join model so I can save list of drills. But now I'm looking for the best way to interact with these objects in the controller.

Should I be calling Activity.drills or Activity.drill_list to get the ordered list?

What is the best way of maintaining the position? Do I have to manually update all of the positions in DrillList?

class Drill < ActiveRecord::Base
  has_many :drill_list, :order => "position"
  has_many :activities, :through => :drill_list, :order => "position"
end

class DrillList < ActiveRecord::Base
  belongs_to :activity
  belongs_to :drill
end

class Activity < ActiveRecord::Base
  has_many :drill_list, :order => "position", :dependent => :destroy
  has_many :drills, :through => :drill_list, :order => "position"  
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

习惯成性 2024-11-09 14:35:18

您应该主要使用drills,drill_list 只是一个中间模型,仅在包含一些额外数据时才应使用。

为了维持仓位,您可以使用索引值,但效率可能不高。相反,如果位置是基于时间的,您可以只按时间排序并获得较新或较旧的练习。

You should mainly use drills, the drill_list is just an intermediate model that should only be used if it holds some extra data.

To maintain the position you can have an index value, but it can be not that efficient. Instead, if the position is based on time, you can just order by time and get the newer or older drills.

悸初 2024-11-09 14:35:18

我意识到这是一篇相当老的帖子,但过去对我来说效果很好的另一个解决方案是 acts_as_list - https://github.com/swanandp/acts_as_list。它是一个古老的宝石,但它工作得很好,并且有一些用于重新排序元素的辅助方法。

作为列表也应该有助于保持位置,而无需您做太多工作。

I realize this is a pretty old post, but another solution that has worked well for me in the past is acts_as_list - https://github.com/swanandp/acts_as_list. It's an old gem, but it works just fine and has some helper methods for reordering elements.

Acts as list should also help maintain the position without much work on your end.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文