简体   繁体   English

如何将参数传递给Rails中的表单,该表单在验证错误时仍然存在?

[英]How do I pass a parameter to a form in Rails that persists on validation error?

I'm attempting to create a hierarchal menu system in rails. 我试图在Rails中创建一个分层菜单系统。 My menu model is in a tree data structure, and I need to pass the parent information to the new action. 我的菜单模型在树数据结构中,我需要将父信息传递给新操作。 The best way i found to do this was to pass the parent's id as a querystring. 我发现做到这一点的最好方法是将父母的ID作为查询字符串传递。 This works, unless validation blocks creation. 除非验证阻止创建,否则此方法有效。 The problem is that after the new view is rendered, the parameter is no longer present in the url. 问题在于,呈现新视图之后,URL中不再存在该参数。

Am i going the wrong way with this? 我在这方面走错了方向吗? Should I just be persisting the value in the session? 我应该只在会话中保留值吗? Should i create a dropdown to pick the parent item (I'd prefer to just let the user click "Add new item here"). 我应该创建一个下拉菜单来选择父项吗(我宁愿让用户单击“在此处添加新项”)。 This must be a common issue, but I havent been able to find antything relevant. 这肯定是一个普遍的问题,但是我还没有找到相关的东西。

Update: To clarify a question, I tried doing the following to pass the parameter when the view is rendered in the failure case, but the url has already been set at that point (we've already posted to the controller's base url). 更新:为了澄清一个问题,我尝试执行以下操作以在失败情况下呈现视图时传递参数,但此时已设置了url(我们已将其发布到控制器的基本url)。

format.html { render :action => "new", :parent_id=> params[:parent_id] }

I need another way to pass the parameter. 我需要另一种传递参数的方法。

I figured it out. 我想到了。 I just added a hidden field to hold the parent_id. 我只是添加了一个隐藏字段来保存parent_id。 When the browser requests the new form, i put the parent_id into the model object, and it's persisted on psotback. 当浏览器请求新表单时,我将parent_id放入模型对象中,并将其持久保存在psotback上。

Not 100% clear on what you are trying to achieve. 您尝试实现的目标还不是100%清楚。

After the operation fails validation, you render the view again? 操作验证失败后,您是否再次渲染视图? Can you not just pass the parent_id to this view as a parameter? 您是否可以仅将parent_id作为参数传递给此视图?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM