I have HABTM relationships between Topic and Chapter Now I want to display chapters in a specific order under topics.
For Eg: A particular chapter might be 2nd chapter under one topic, and might be 8th chapter under another topic.
How Should I do it? Thanks in advance.
In this case you have a non-trivial many-to-many relationship, the join table needs to contain more than just foreign keys to each of main tables.
As a result, you’ll want to move from HABTM to
has_many :throughon both Topic and Chapter, and change the join table to be its own model that not only relates the two main tables to each other, but also stores the order in a column (which, by the way, you should not name “order”, since it will confuse SQL and Rails :-).Converting from a standard Rails HABTM model is pretty easy, but one bit of advice: think of what it is that makes what used to be just a join table a real model … and use that as a name for the new model (and associated new table). In a simple HABTM, you would create a table
chapters_topics, when it becomes a model it might be “ChapterTopic” (resulting in a tablechapter_topics).