I have a nested form which creates many locations for each post. Each location can also be used in multiple posts.
E.g. Post 1 may have Location1, Location2 and Location3
AND Post 2 may have Location1, Location4 and Location5
I want these locations to be ordered within the posts in the same order that they were added. I assume the easiest way to do this is to add an ‘order’ column to the joining table (Posts_Locations) however i’m not sure how to set this up or define :order_by in my controller. Should I do this with directly with SQL?
Any suggestions? Is this the best way to do this?
If you’re using a simple join table and the
has_and_belongs_to_manyfor both Post and Location, you may want to make the posts_locations table a model in its own right, joining the two usinghas_many :through. This is well described here in this Rails guide.Bonus hint: when you’re adding the new column, change the model, and thus join table name to something singular, like PostLocation which will result in a table name
post_locations… or perhaps something more descriptive. Also, don’t use the word “order” for this field, since it’s a keyword in both rails and SQL. Maybe call it “display_order”?Then in the PostLocation model you might create a scope, or even a default scope that defines the proper order., e.g.
scope :sorted, order("display_order DESC")The other question I might ask: is it really the case that the order of the Posts is linked to whichever location and vice-versa?