使用 has_many :through 创建有序列表
我设置了一个 has_many :through 与连接模型上的位置列关联,这样我就可以保存练习列表。但现在我正在寻找与控制器中的这些对象交互的最佳方式。
我应该调用 Activity.drills
或 Activity.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该主要使用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.
我意识到这是一篇相当老的帖子,但过去对我来说效果很好的另一个解决方案是
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.