ruby24
ruby24

Reputation: 309

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

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!

Upvotes: 0

Views: 749

Answers (1)

SRack
SRack

Reputation: 12203

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.

Upvotes: 1

Related Questions