I’m trying to set up an item model and a tag model that have a many-to-many relationship (items have multiple tags and tags belong to multiple items). I’m using Rails and Backbone.js, so I need to have them store, retrieve and update models seamlessly between each other. I would also love it if I could save a new list of tags for a specific item in one go from the client.
What’s the correct way to structure the models and controllers on the Rails side and the models on the Backbone side to keep the system RESTful and make it easy to share models between them? Specifically, what would the API look like on the server, and what would the JSON representation of the models be in saving and retrieving them?
I would really appreciate any advice on structure, and I don’t really need any code or implementation details — just a high level setup would be great. Thanks!
[In addition to Pope’s answer:]
For reference, the Rails answer (from Creating multiple resources in a single RESTful POST in rails) is to use
accepts_nested_attributes_for:The following assumes that you’ve added
ActiveRecord::Base.include_root_in_json = falseto one of your initializers (see here for why).To save a list of tags for an item from Backbone, the answer (from Saving nested objects with Rails, backbone.js, and accepts_nested_attributes_for) is to override
syncon the Item model:This solution might require a bit more hackery to get Rails to understand Backbone, but this is how you would start setting them up.