rails 3 accepted_nested_attributes_for不拒绝空嵌套file_field

时间:2013-05-28 20:09:11

标签: ruby-on-rails lambda nested nested-forms nested-attributes

对rails很新,我试图拒绝一个空的嵌套文件_field,但它只是继续。这是设置。

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

Fihish模型

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 partial

.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

0 个答案:

没有答案