S_A
S_A

Reputation: 423

Create a path to a nested resource in Rails

I had to create a new controller action called Copy:

def Copy
    old_record = @deal.contract.find(params[:id])
    new_record = old_record.dup
    new_record.save
end

I need to access a contract that belongs a deal.

How should I create a link_to on view to redirect to an url like that mydomain.com/deal/1/contract/2 ?

In this case I'd like to access the contract number 2 that belongs to deal 1.

How should configurate my routes file?

Upvotes: 0

Views: 519

Answers (1)

max
max

Reputation: 102250

You can setup nested routes by using resources or its singular brother resource.

resources :deals do
  resources :contracts do
    member do
      post :copy
    end
  end
end

This would create a nested path such as /deals/:deal_id/contracts/:id/copy. Note that it is declared as POST since a get request should not create resources.

You can create paths and urls to nested resources like so:

path_to([@deal, @contract])
link_to(@contract.name, [@deal, @contract])
form_for([@deal, @contract])
redirect_to([@deal, @contract])

However you may want to start by reading up on when and how to use nesting:

Upvotes: 3

Related Questions