0

Rails 新手,我试图拒绝一个空的嵌套 file_field,但它仍在继续。这是设置。

编辑:如果包含一个图像,它实际上会正确保存图像,只是不会拒绝空图像。

鱼模型

class Finish < ActiveRecord::Base
  default_scope order('finishes.id ASC')
  attr_accessible               :name, 
                                :title,

                                ##belongs_to##
                                :sku_id,

                                ##has_many##
                                :image_attributes


  belongs_to                    :skus

  has_one                       :image, as: :imageable, :dependent => :destroy
  accepts_nested_attributes_for :image, :reject_if => lambda { |a| a[:asset].blank? }, :allow_destroy => true

  validates_presence_of         :title

  before_save                   :create_name

  private

  def create_name
    self.name = title.parameterize
  end
end

饰面控制器

def new
  @finish = Finish.new

  @finish.build_image

  respond_to do |format|
    format.html # new.html.erb
    # format.json { render json: @finish }
  end
end

图像模型

class Image < ActiveRecord::Base
  attr_accessible               :content, #remove if no longer necessary
                                :asset

  belongs_to                    :imageable, polymorphic: true

  mount_uploader                :asset, ImageUploader
end

形式

= form_for @finish, :html => { :multipart => true } do |f|
  - if @finish.errors.any?
    #error_explanation
      %h1= "#{pluralize(@finish.errors.count, "error")} prohibited this finish from being saved:"
      %ul
        - @finish.errors.full_messages.each do |msg|
          %li= msg

  %fieldset{id: "finishes"}
    .field
      = f.label :title
      = f.text_field :title

    #finish-image.images
      = f.fields_for :image do |image_builder|
        = render 'images/image_fields', f: image_builder

  .actions
    = f.submit 'Save'

image_fields 部分

.field
  = f.label :asset, "Image"
  = f.file_field :asset

- if f.object.asset
  .image-box
    = image_tag f.object.asset_url(:thumb).to_s


.remove-fields
  = link_to_remove_fields f
4

0 回答 0