Rails:恢复使用 form_tag 的非模型表单的内容
我的第一个 Rails 应用程序(使用 Rails 3)取得了良好的进展。 MVC 交互一切顺利,但我在处理与模型不直接相关的表单时遇到了困难。
我正在使用 form_tag,如果成功,一切都会正常。但对错误的处理有些不友好。实际的错误消息存储在Flash中并通过layouts/application.html很好地显示,但如果表单能够记住用户刚刚填写的内容,我真的很喜欢它。但事实并非如此:所有字段重置为默认值。
我喜欢对象上的 RESTful 操作表单自动记住其提交的值,并在出现错误时以红色突出显示的方式。没有红色突出显示我很好,但如果我能让表单的字段保留提交的值,我真的很喜欢。
谁能建议如何做到这一点?
相关文件摘录:
views/cardsets/import.html.erb:
<%= form_tag :action => :import_data, :id => @cardset do %>
...
<%= text_field_tag "separator", "", :maxlength => 1 %>
...
<%= text_field_tag "formatting_line" %>
...etc (more fields)
controllers/cardsets_controller.rb:
# POST /cardsets/1/import_data
def import_data
success, message = @cardset.import_data(params, current_user)
if success
redirect_to(@cardset, :notice => message)
else
flash.now[:error] = message
render :import
end
end
I'm making good progress with my first Rails app (using Rails 3). The MVC interaction is all going fine, but I'm having difficulty with a form that doesn't relate directly to a model.
I'm using form_tag, and in the case of success, everything behaves fine. However, the handling of errors is somewhat unfriendly. The actual error message is stored in the flash and displayed fine by layouts/application.html, but I'd really like it if the form could remember the contents that the user had just filled in. But it doesn't: all the fields reset to their default values.
I love the way that forms for RESTful actions on objects automatically remember their submitted values, and get highlighted in red if there are errors. I'm fine without the red highlight, but I'd really like it if I could make the form's fields keep the submitted values.
Can anyone advise how to do this?
Excerpts from the relevant files:
views/cardsets/import.html.erb:
<%= form_tag :action => :import_data, :id => @cardset do %>
...
<%= text_field_tag "separator", "", :maxlength => 1 %>
...
<%= text_field_tag "formatting_line" %>
...etc (more fields)
controllers/cardsets_controller.rb:
# POST /cardsets/1/import_data
def import_data
success, message = @cardset.import_data(params, current_user)
if success
redirect_to(@cardset, :notice => message)
else
flash.now[:error] = message
render :import
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
text_field_tag 的第二个参数是填充字段的值。尝试这样的事情:
The second arg to text_field_tag is the value to fill in the field with. Try something like this:
如果您的字段有默认值,您将需要从表单的“show”操作中设置它:
或直接在模板上设置(不太好,因为每次都使用
||
并添加更多控制器数据查看):If your field has a default, you will want to set it from the "show" action for the form:
or directly on the template (less good because uses an
||
every time and adds more controller data to view):