Let’s imagine a CMS where Article can belong to either User or Company. With polymorphic relations we can model it like this:
We seed our DB:
Users and Companies need to do CRUD operations on their Articles. Separately CMS internal editors need to CRUD operations on ALL articles. We create routes like this:
Now we need to implement controllers
Browsing to http://localhost:3000/articles will show all Articles. Browsing to http://localhost:3000/users/1/articles and http://localhost:3000/companies/1/articles will filter articles for specific user / company.
When we browse to http://localhost:3000/users/1/articles and click Show on specific Article we want to be taken to http://localhost:3000/users/1/articles/1. By default the <%= link_to 'Show', article %> will take us to http://localhost:3000/articles/1.
To return to proper index route we modfiy
But this puts the biz logic into our ERB files which will be hard to test. Let’s create a separate PORO.
Now we can replace our link_to helpers in ERB files with these:
To restrict permissions so Users and Companies can view/edit only their own Articles we can implement Pundit or CanCanCan. I recenly wrote a post about that.