Let’s see if I can explain myself well enough about the doubts I have.
I have a User model that is managed by Devise. So in my routes I have:
devise_for :users
In the User model, I have an association with the model Plan. The assocation is:
User has_many Plans
Plan belongs_to User
At this point I also have a resource for the Plan model, so I can fetch all the Plans, show a particular plan and so on. But I want to go further.
I want to be able to see plans of a particular User and let a particular User to see his own plans and edit them.
So, for example, whenever I go to:
/users/:id/plans
I want to be able to see the plans for that particular :id user. And if the user who is visiting that url is the one that is logged in, I want him to be able to edit those plans.
How can I manage all this behavior? Is there any gem out there that helps with it? Or I need to do conditionals in the views saying if current_user…
Let’s start with routes, you can make your routes like this:
I used
resources :plansinsideresources :usersto have route like this/users/:user_id/plans, while theresources :plansoutside is for the rest of the actions (edit, destroy, …) that don’t require auser_id, i.e., a plan is identified by a unique id so you don’t need auser_idto fetch it from the db for editing or destroying.Now for the controller, we can make it like this: