Rails 3 Render =>参数新增 [英] Rails 3 Render => New with Parameter
问题描述
我读过: 轨道:使用render:action?传递参数,但我仍然有问题.
我在新页面上的URL是: http://localhost:3000/submit?category_id = 2 .第一次提交表单没有任何问题,但是如果创建失败并且控制器呈现新页面,我会收到一个错误,因为没有传递参数,所以没有id的类别找不到.
这是new.html.erb和new/create控制器的简短版本
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
下面的第1行给我错误.
<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 %>
感谢您的帮助.我已经转了好几个小时.
我认为您的'create'方法的else子句将需要大致反映您的'new'方法,这意味着再次从params
填充@category
>哈希.
因此,首先请确保您的隐藏字段已填充,然后在提交表单时检查params
的内容. category_id
应该在那儿,如果保存失败,您需要像在"new"中一样再次抓住它.
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.
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.
这篇关于Rails 3 Render =>参数新增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!