This is a simplified example of what I'm trying to achieve, I'm relatively new to Rails and struggling to figure out the relationships between the models.
I have two models: the User model and the Category model. A user can be associated with many categories. A specific category may appear in the list of categories for many users. If a certain category is deleted, this should be reflected in the list of categories for the user.
In this example:
My Categories table contains five categories:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| ID | Name |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| 1 | Sports |
| 2 | News |
| 3 | Entertainment |
| 4 | Technology |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
My Users table contains two users:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| ID | Name |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| 1 | UserA |
| 2 | UserB |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The user can select Sports and Technology as their categories
User can select News, Sports and Entertainment
The sport category is deleted, and the UserA and UserB category lists reflect the deletion
I played with creating a UserCategories table that contains the identifiers of both the category and the user. This view worked, I could search for category names, but I could not get cascading deletion to work, and the whole solution just seemed wrong.
The examples of using the belongs_to and has_many functions that I found seem to discuss mapping a one-to-one relationship. For example, comments on a blog post.
- How do you imagine this many-to-many relationship using the built-in Rails function?
- Does it use a separate table between two viable solutions when using Rails?
ruby-on-rails
fletcher Feb 25 2018-11-17T00: 00Z
source share