Nested Resources Rails

Asked

Viewed 112 times

1

I created two models in the Rails application, and made their relationship through the declaration in the classes and in the bank as well. I added the configuration to enable nested Resources in the Routes file, the routes were created but do not work the way they should, I will put the example below:

Model Project
has_many :steps

Model Steps
belongs_to :project

resources :projects  do
    resources :steps
end

However, when I hit the /Projects/1/Steps url 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??

  • Boy, got confused... you set the action index Steps? Or are you asking if you have to define...

1 answer

1

What’s happening is exactly what it should be. With the command rake routes it is possible to see the following result:

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

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

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

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 for 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.