0

Rails newbie having a question about storing the order of associations. 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). But even with the question_list model, I don't really know how to retain order. 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?

Thanks in advance for any suggestions!

ruby24
  • 309
  • 1
  • 15
  • There is an *almost* standard gem in order to manage sorted records: https://github.com/swanandp/acts_as_list Otherwise you could add a `position` column and manage it manually – mdesantis Jun 12 '18 at 08:43

1 Answers1

1

Personally, I'd recommend using acts_as_list - it makes reordering a breeze. 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) }. This will ensure your questions are retrieved in the order expected.

The gem itself actually recommends adding the order directly to the association:

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. In your case, in the Question model:

acts_as_list scope: :survey, column: :rank_id

And in the Survey model:

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

Happy to expand on any of that if you need - let me know.

SRack
  • 11,495
  • 5
  • 47
  • 60
  • 1
    Amazing, thanks! Was a bit wary of adding dependencies early on, didn't know acts_as_list was as "standard". – ruby24 Jun 12 '18 at 09:37
  • 1
    You're welcome, happy to help - I remember having the same dilemma, and coming across a number of edge cases and performance problems when going it alone. Hope this works out well! – SRack Jun 12 '18 at 10:00