Rails: nesting the same resource in multiple nested quiet routes?

It's pretty easy, but switching between frameworks / languages ​​makes me doubtful. Trying to work out routes for has_many :through relationships in Rails.

 #User has_many :reservations, :dependent => :destroy has_many :events, :through => :reservations #Reservation belongs_to :user belongs_to :event #Event has_many :reservations, :dependent => :destroy has_many :attendees, through => :reservations, :source => :user 

I need routes where from the user model I can quickly create / create a new reservation for a specific event (& vice versa), but I don’t know how to do it. It looks weird:

 resources :users do resources :reservations, only: [:new, :create, :destroy] end resources :events do resources :reservations, only: [:new, :create, :destroy] end 

In any case, just looking for confirmation, or perhaps an alternative way to deal with it. Ideally, there is a link on the page next to the event that the user could click and (either through ajax or reload the page), they would make a “reservation”.

Similarly, I need a route to see every user who has a reservation for this event. And every event for which this user is reserved.

+4
source share
2 answers

Good question! I think I will go with this set of routes:

 resources :events do resources :reservations, only: [:new, :create, :destroy] end resources :users do get 'reservations', :on => :member end 

Your reservations will be closely related to events. I think this makes sense in terms of modeling. Based on your description, it sounds like a logged in user will click a link to create a reservation when it is under an event. By comparing reservations with events, you know which event to create the reservation is just from the route, and since you have an authenticated user, you can guess which user to use (probably from your session). For example, a route such as POST to /events/5/reservations will create a reservation for the current user registered for event 5.

The optional get action on the user resource provides an endpoint for answering the question What reservations does a particular user have?

Ideally, you want to have only one set of endpoints for resource management. In terms of getting more information through actions other than resources, it depends more on preferences and what use cases you want to support.

+7
source

I would use this for DRY routes:

 def reserv resources :reservations, only: [:new, :create, :destroy] end resources :users do reserv end resources :events do reserv end 
+1
source

All Articles