Reputation: 275
I have an app with online trainings and every online training has several chapters. I don't want to create next controller just for training chapters. I want to have new action in TrainingsController which might be called chapter. Then I want URL like this:
/trainings/1/chapter/3
(/controller/id of training/action/id of chapter)
Could you please help me how can I set routes.rb to achieve this behaviour? I tried lot of things, but it's still broken.
Thank you in advance!
Petr
Upvotes: 1
Views: 51
Reputation: 4053
I think here is what you are looking for:
match '/trainings/:training_id/chapter/:chapter_id' => 'trainings#chapter', :as => 'chapter_training'
app/controllers/trainings_controller.rb
def chapter
end
Upvotes: 1
Reputation: 38645
You could define the route as:
resources :trainings do
get 'chapter/:chapter_id', action: :chapter, as: :training_chapter, constraints: { chapter_id: /\d+/ }
end
Then in your trainings_controller.rb
:
def chapter
# params[:chapter_id]
...
end
The line get 'chapter/:chapter_id', action: :chapter, as: training_chapter, constraints: { chapter_id: /\d+/ }
, defines a get
route of format training/:id/chapter/:chapter_id
which executes the chapter
action in TrainingController
.
The name of this route is training_chapter
defined by as: :training_chapter
, so you can use the named route helpers such as training_chapter_trainings_path
.
The final option constraints: /\d+/
is restricting the values that chapter_id
can hold, based on which this route gets executed. So, a get request to /trainings/1/chapter/1
executes the chapter
action, whereas /trainings/1/chapter/a
does not because the value a
for chapter_id
is non-digit.
Upvotes: 3