Reputation: 2777
I have a nested resource as so:
resources :contacts do
resource :leads
end
When I render the edit view, the url looks as so:
http://localhost:3000/contacts/1/leads/1
When I submit the form and it goes to leads controller update action:
def update
if @lead.update_attributes(lead_params)
redirect_to contact_lead_path(@lead.contact, @lead)
else
render :edit
end
end
When else is triggered, it renders the page as so:
http://localhost:3000/leads/1
when it should be:
http://localhost:3000/contacts/1/leads/1/edit
Why doesn't "render :edit" account for the full nested url? How can I resolve this?
Upvotes: 2
Views: 300
Reputation: 1995
Look at the way your form is set up in your view. It should be something like the following. Your LeadsController#edit
method will need to load both @contact
and @lead
.
<%= form_for [@contact, @lead] do |f| %>
...
<% end %>
The fact that you're getting the non-nested-resource url from the form suggests that you're not using this pattern, and you should.
Also, I assume this was a typo, but in your question, you're declaring the nested route as
resource :leads
instead of
resources :leads
The singular resource
is valid, but it means something different than what you're intending here, i.e., that each contact
has one associated lead
.
Upvotes: 1
Reputation: 96
When using render
, the URL seen in the address bar will be the URL that the user was sent to when they submitted the form. In the case of your form, it looks like the URL the edit form submits to is:
PATCH /leads/1
When you render
, it basically sends the content stream as a response to that request. So if you want your render :edit
call to go to /contacts/1/leads/1/edit
you need to define a route that responds to
PATCH /contacts/1/leads/1/edit
and map that to your leads#update
action then set the url of your form to that URL. But I'd advise against that since you'd be straying far from Rails conventions.
Upvotes: 0