Rails:如果字段为空,则阻止提交表单 [英] Rails: prevent submitting form if field is blank

查看:162
本文介绍了Rails:如果字段为空,则阻止提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建产品页面,用户可以在其中上传多张产品照片.为了创建和编辑产品,我正在渲染一个表单文件.为了上传照片,我使用了nested_fields产品形式的照片.表单中的照片代码如下所示:

I am creating product page, where user can upload more than one photo of product. To create and edit product, i am rendering a form file. For uploading photos, i have used nested_fields for photos in the form of the product. Here is how photo code in the form looks like:

<%= f.fields_for :photos do |photo| %>
   <%= image_tag photo.object.avatar.url(:thumb), unless f.object.new_record? or photo.object.new_record? %>
   <%= photo.file_field :avatar, :style => "none" %>
   <%= photo.link_to_remove "Remove"%>
<% end %>
<%= f.link_to_add 'Add Photos', :photos, "data-association-insertion-node"=> ".photos",   "data-association-insertion-position" => "append", "data-type" => "link"%> 

在产品型号中,

has_many :photos, :as => :attachable, :dependent => :destroy
accepts_nested_attributes_for :photos, :allow_destroy => true

当用户创建产品时,我已经使用照片进行验证.因此,用户必须上传照片.这件作品工作正常.

When user creates product, i have used validation for presence of photo. So, user has to upload a photo. This piece is working properly.

在照片模型中:

validate :validates_account_avatar

但是问题出在编辑中.用户可以删除所有照片.在这里,我要防止用户删除所有照片.

But the problem is in edit. User is able to remove all the photos. Here i want to prevent user from removing all the photos.

在提交修改后的产品时,如何通知用户照片字段不能为空白或至少要有一张照片.

How to notify user that photo field can't be blank or at least one photo should be present while submitting edited product.

我试图用这个:

accepts_nested_attributes_for :photos, :allow_destroy => true, :reject_if => lambda { |a| a[:avatar].blank? }

但没有用.

帮助!

推荐答案

使用jquery验证插件.

Use jquery validation plugin.

http://bassistance.de/jquery-plugins/jquery-plugin-validation /

这篇关于Rails:如果字段为空,则阻止提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆