Nested resources Rails

1

I created two models in the Rails application, and made their relationship through the declaration in the classes and in the database as well. I added the configuration to activate the nested resources in the routes file, the routes were created but they do not work the way they should, I'll put the example below:

Model Project
has_many :steps

Model Steps
belongs_to :project

resources :projects  do
    resources :steps
end

However, when I hit url / projects / 1 / steps it always falls into the index action of the Steps controller, which returns a Steps.all.

The correct way to do this, is just rewriting the same index action ??

    
asked by anonymous 05.05.2016 / 02:56

1 answer

1

What is happening is exactly what it should be. With the command rake routes you can see the following result:

       Prefix Verb   URI Pattern                                    Controller#Action
project_steps GET    /projects/:project_id/steps(.:format)          steps#index

That is, its URL /projects/:project_id/steps is pointing to the controller steps and the action index .

If you want to direct to a specific action other than index, you can create a route for it as:

resources :projects  do
  resources :steps do
    get :minha_acao, on: :collection
  end
end

Which will respond to:

/projects/:project_id/steps/minha_acao

If you change collection to member the URL will be:

/projects/:project_id/steps/:step_id/minha_acao

Note also that the verb created was GET, but could also be POST, PUT or DELETE, depending on your need.

    
05.05.2016 / 21:45