I think I am stumbling upon a rendering/redirection issue. In my rails application I have clients who can have many projects. When I update a project I use a nested form with the form_for method, passing it a client and project instance variable, respectively.
Here is my code:
routes.rb:
resources :clients do
resources :projects
end
projects_controller.rb
def edit
@client = Client.find(params[:client_id])
@project = Project.find(params[:id])
end
def update
@project = Project.find(params[:id])
respond_to do |format|
if @project.update_attributes(params[:project])
format.html { redirect_to client_project_path(@project.client, @project), notice: 'Project was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" } # !!this seems to be the problem
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
views/projects/_form.html.erb:
<%= simple_form_for([@client, @project]) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :title %>
<%= f.input :start_on %>
<%= f.input :end_on %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
When I simply display the edit action, everything works fine. If I update the project with valid data, everything is fine, too. The problem occurs when I type in invalid or missing data into the form – then the “else part” of the update method is called, and the action “edit” should be rendered.
This indeed happens, but it seems to me that something is wrong either with the “edit” method or my form, because when I change render action: "edit" to redirect_to action: "edit", it does redirect me (of course without error messages so it is clearly not the desired solution, but I just wanted to test).
When “edit” is rendered, this is the error message I am getting:
undefined method `project_path'
which is only referring to the first line in my form.
What am I doing wrong here? Sorry for the long question and thanks for any help!
You need to load your @client variable in the update action. Think of it this way, if you hit the else, what did the edit provide to the view, because you need just that when you render instead of redirect. Being that your resources are nested, the form_for helper needs both the client and the project.