Rails: prevent submitting form if field is blank

点点圈 提交于 2019-12-12 03:49:08

问题


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"%> 

In product model,

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.

In photo model:

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.

I tried to use this:

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

but no use.

Help!


回答1:


Use jquery validation plugin.

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



来源:https://stackoverflow.com/questions/15655892/rails-prevent-submitting-form-if-field-is-blank

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!