I'm experimenting with using has_and_belongs_to_many relationships between two of my resources (users and patterns; users can "favorite" a pattern) rather than a has_many :through. I don't need any additional attributes on the join table, which is why (based on the Rails guide to Active Record Associations) I've chosen this path.
The join table that is created (using bundle exec rails g migration CreateJoinTablePatternUser pattern user) is called patterns_users. I don't have a controller or a model for this join, as per the advice in the guide.
Obtaining all of a user's favorites is possible through user.patterns, so I don't think I need a route there. To create a new favorite, though, I'll need some way to post to the join table directly.
I'm leaning toward making a POST request to /patterns/:pattern_id/favorite, and defining a create_favorite route in PatternsController to add the pattern in question to the user's list of favorites.
Is there a better/more semantic approach? Specific questions:
- I have in my head for some reason that
POST generally goes to a route that ends in a plural. If that's an accurate heuristic, should my route be /patterns/:pattern_id/favorites?
- Is
favorites/:pattern_id better than a nested route?
- Should I scrap the
has_and_belongs_to_many approach and just do a has_many :through, with a favorite model / favorites controller?
Not sure any of this will affect my functionality in any way, but I'm curious whether there's a best practice.
I'm experimenting with using
has_and_belongs_to_manyrelationships between two of my resources (users and patterns; users can "favorite" a pattern) rather than ahas_many :through. I don't need any additional attributes on the join table, which is why (based on the Rails guide to Active Record Associations) I've chosen this path.The join table that is created (using
bundle exec rails g migration CreateJoinTablePatternUser pattern user) is calledpatterns_users. I don't have a controller or a model for this join, as per the advice in the guide.Obtaining all of a user's favorites is possible through
user.patterns, so I don't think I need a route there. To create a new favorite, though, I'll need some way to post to the join table directly.I'm leaning toward making a
POSTrequest to/patterns/:pattern_id/favorite, and defining acreate_favoriteroute inPatternsControllerto add the pattern in question to the user's list of favorites.Is there a better/more semantic approach? Specific questions:
POSTgenerally goes to a route that ends in a plural. If that's an accurate heuristic, should my route be/patterns/:pattern_id/favorites?favorites/:pattern_idbetter than a nested route?has_and_belongs_to_manyapproach and just do ahas_many :through, with afavoritemodel /favoritescontroller?Not sure any of this will affect my functionality in any way, but I'm curious whether there's a best practice.