如何将参数传递给Rails中持续存在验证错误的表单?

时间:2021-10-04 07:25:01

I'm attempting to create a hierarchal menu system in 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. 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.

我正在尝试在rails中创建一个层级菜单系统。我的菜单模型是树数据结构,我需要将父信息传递给新操作。我发现这样做的最好方法是将父亲的id作为查询字符串传递。这有效,除非验证块创建。问题是在呈现新视图后,该参数不再出现在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.

我需要另一种传递参数的方法。

2 个解决方案

#1


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作为参数传递给这个视图?

#2


I figured it out. I just added a hidden field to hold the 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。当浏览器请求新表单时,我将parent_id放入模型对象中,并将其保留在psotback上。

#1


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作为参数传递给这个视图?

#2


I figured it out. I just added a hidden field to hold the 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。当浏览器请求新表单时,我将parent_id放入模型对象中,并将其保留在psotback上。