问题
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