简体   繁体   English

Rails:如何存储自定义顺序/关联等级(postgres)

[英]Rails: How to store custom order / rank of associations (postgres)

Rails newbie having a question about storing the order of associations. Rails新手对存储关联顺序有疑问。 Background is I'm thinking about building a super simple survey app for learning purposes. 背景是我正在考虑构建一个用于学习目的的超级简单的调查应用程序。 The idea is to have multiple surveys and corresponding questions. 这个想法是要进行多次调查和相应的问题。

Models are straightforward: 模型很简单:

class Survey
  has_many :questions
end

class Question
  belongs_to :survey
end

My question now - where and how would you store the custom order / sequence of the questions in the survey? 我现在的问题-您将在哪里以及如何在调查中存储问题的自定义顺序/顺序? Questions may be moved around, added and removed and should retain answers from survey responses. 问题可以四处移动,添加和删除,并且应保留调查回答中的答案。

I was thinking about introducing a "rank_id" (inside the question or survey model?), or some kind of new question_list model ( survey has_one :question_list, has_many :questions through :question_list ). 我正在考虑引入“ rank_id”(在问题或调查模型内部吗?),或某种新的question_list模型( survey has_one :question_list, has_many :questions through :question_list )。 But even with the question_list model, I don't really know how to retain order. 但是,即使使用question_list模型,我也不知道如何保留顺序。 Googling led me to Saving the order of associated records in a Rails has_many :through association and it recommends the acts_as_list gem , but that seems like too much for this use case? Googling导致我将关联记录的顺序保存在Rails has_many:through关联中 ,并建议使用acts_as_list gem ,但是对于这种用例来说似乎太多了?

Thanks in advance for any suggestions! 在此先感谢您的任何建议!

Personally, I'd recommend using acts_as_list - it makes reordering a breeze. 就个人而言,我建议您使用acts_as_list它使重新排序变得轻而易举。 It doesn't seem like overkill here, rather the correct scenario for it :) 在这里似乎并不过分,而是正确的方案:)

You can then add a default order to the Question model, using: default_scope { order(:rank_id) } . 然后,您可以使用: default_scope { order(:rank_id) }将默认顺序添加到Question模型。 This will ensure your questions are retrieved in the order expected. 这将确保按预期顺序检索您的问题。

The gem itself actually recommends adding the order directly to the association: gem本身实际上建议将order直接添加到关联中:

has_many :todo_items, -> { order(position: :asc) }

It also defaults to using a column named position instead of rank_id , though you can overwrite this. 尽管您可以覆盖此列,但它也默认使用名为position的列而不是rank_id In your case, in the Question model: 在您的情况下,在Question模型中:

acts_as_list scope: :survey, column: :rank_id

And in the Survey model: Survey模型中:

 has_many :questions, -> { order(rank_id: :asc) }

Happy to expand on any of that if you need - let me know. 如果您需要,很高兴扩展任何内容-告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM