samedi 26 septembre 2015

How validate

I have a two model

Gallery

class Gallery < ActiveRecord::Base
    has_many :pictures, :dependent => :destroy

    accepts_nested_attributes_for :pictures, :allow_destroy => true

    attr_accessible :name, :description, :pictures_attributes

    validates_presence_of :pictures
end

Picture

    class Picture < ActiveRecord::Base
      belongs_to :gallery

      has_attached_file :image,
        :path => ":rails_root/public/images/:id/:filename",
        :url  => "/images/:id/:filename"
    end

And form

    <%= form_for @gallery, :html => { :class => 'form-horizontal', multipart: true } do |f| %>
    .........
     <div class="controls">
          <%= file_field_tag "images[]", type: :file, multiple: true %>
        </div>
    .........
    <% end %>

Controller

def create
    @gallery = Gallery.new(gallery_params)

    respond_to do |format|
      if @gallery.save

        if params[:images]         
          params[:images].each { |image|
            @gallery.pictures.create(image: image)
          }
        end

        format.html { redirect_to @gallery, notice: 'Gallery was successfully created.' }
        format.json { render json: @gallery, status: :created, location: @gallery }
      else
        format.html { render action: "new" }
        format.json { render json: @gallery.errors, status: :unprocessable_entity }
      end
    end
  end

If I want to validate has_many pictures image blank?, I got every time a error that Pictures is blank, even I selected images.

How I validate has_many association with multiple image field?

Aucun commentaire:

Enregistrer un commentaire