Rails 3 Render => New with option

I read: Rails: pass parameters using 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 for the first time works without any problems, but if the creation fails and the controller displays a new page, I get an error message, I can not find a category without id, because the parameter is not 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 gives me an 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 drove around for hours.

+1
source share
1 answer

I think that the else clause of your create method will approximately mirror your "new" method, which means re-populating @category from your params hash.

So, first make sure your hidden field is completed, and then check the contents of params when submitting the form. category_id should be there, and you will need to capture it again, as in the "new" if the failure failed.

+1
source

All Articles