2

I'v read: Rails: Pass parameters with render :action? ,but I'm still having problems.

My URL for the new page is: http://localhost:3000/submit?category_id=2. Submitting the form the first time works without any problems, but if the creation fails and the controller renders a new page I get an error can't find category without id because the parameter is not being passed.

Here's a short version of the new.html.erb and new/create controllers

def new
    ...
    @category = params[:category_id]
    @title = "Submit a review"
  end

  def create
    ....
    if @review.save
      flash[:success] = "New a Created"
      redirect_to user_path(@user)
    else
      @title = "New Review"
      render :action => 'new', :category_id => @category     
    end
  end

Line 1 below is giving me the error.

<h1>Blah, blah, blah<%= "best #{Category.find(@category).name}" %></h1>
<br />
<%= form_for(...) do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
  <tr>
    <td> <%= select_tag(... %></td>
    <td><%= collection_select(...) %><br /> %></td>
    <td><%= f.text_field ... %></td>
  </tr>
</table>
        <%= f.hidden_field :category_id, :value=>@category %>
<div class="actions">
      <%= f.submit "Add" %>
 </div>
<% end %>

Any help is appreciated. I've been going in circles for hours.

Community
  • 1
  • 1
John
  • 4,362
  • 5
  • 32
  • 50

1 Answers1

1

I think the else clause of your 'create' method will need to roughly mirror your 'new' method, which means populating @category again from your params hash.

So first make sure your hidden field is populated, then check the contents of params when the form is submitted. category_id should be there and you'll need to grab it again as you did in 'new', if the save fails.

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
TK-421
  • 10,598
  • 3
  • 38
  • 34
  • Thank you, I moved the @category to the else statement, and I can see that the @category variable is not nil in the create controller from the enviroment dump. However, the value is still not passing through the render and the error message remains the same. Any other ideas? – John Jan 12 '11 at 23:46
  • Update: After retyping everything again. The new parameter was correct but in the else render the parameter should be @category= [:review][:category_id]. Thank you for your help. – John Jan 13 '11 at 00:04