将错误条件移出视图。(Moving error conditionals out of the view.

编程入门 行业动态 更新时间:2024-10-22 14:29:30
将错误条件移出视图。(Moving error conditionals out of the view. -Rails)

我有一个名称为文本字段的表单,它有一个在线验证。 当用户忘记输入名称时,文本字段会变成红色,这很好,但我想清理一下我的视图,但我不确定如何? 也许是帮手? 也许是一种方法? 我有点新的轨道,我正在寻找这个问题的一些建议。 这是我的视图代码。

视图

<% if f.object.errors[:name].present? %> <%= f.text_field :name, :class => 'alert' %> <div class="validation"> <% f.object.errors[:name].each do |error| %> <%= error %> <% end %> </div> <% else %> <%= f.text_field :name %> <% end %>

这是一个非常标准的说法,但是我认为它对于视图来说有点太难看了。

I have a form that has a text field for name, it has a presence validation on it. When a user forgets to input the name the text field turns red this is all fine but I'd like to clean up my view a little bit but I'm not sure how? Maybe a helper? Maybe a method? I'm a bit new to rails and I'm looking for some advice on this problem. Here is my code for the view.

VIEW

<% if f.object.errors[:name].present? %> <%= f.text_field :name, :class => 'alert' %> <div class="validation"> <% f.object.errors[:name].each do |error| %> <%= error %> <% end %> </div> <% else %> <%= f.text_field :name %> <% end %>

It's a pretty standard if else statment but I'd think its a little too ugly for the view.

最满意答案

您可以使用模型验证获得类似的结果。 如果您需要在模型上进行在场验证,那么它会告诉用户该字段不能为空。 这可以让你告诉用户他们不能将表单字段留空,而无需在视图中手动编码。

示例:发布模型 - app / models / post.rb

class Post < ActiveRecord::Base validates :title, :presence => true validates :body, :presence => true end

如果用户现在尝试将标题或正文的表单提交为空,那么他们将被要求重新提交表单,并附带一个小工具提示“请填写此字段”。

视图中不需要任何逻辑来实现这一点,只需验证模型中的存在即可。

You can achieve a similar result using your model validation. If you require a presence validation on a model, then it will tell the user the field cannot be blank. This would allow you to tell the user they cannot leave a form field blank without manually coding this in your views.

Example: Post Model - app/models/post.rb

class Post < ActiveRecord::Base validates :title, :presence => true validates :body, :presence => true end

If the user now attempts to submit the form with either Title or Body empty then they will be asked to resubmit the form, with a little tool tip saying "Please fill out this field".

No logic is needed in the view to achieve this, simply validate presence in your model.

更多推荐

本文发布于:2023-08-06 06:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1446048.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   移出   错误   条件   conditionals

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!