在导轨

时间:2016-04-08 02:47:46

标签: ruby-on-rails ruby image upload image-gallery

我是Ruby on Rails的新手。我正在创建一个可以在照片库中存储照片的应用。我尝试使用回形针上传照片,但它已成功运行。但现在我想用回形针同时在同一个画廊中添加多张照片。我没有得到如何实现它。任何人都可以帮助我吗?

在gemfile中,我写过" gem' paperclip'"。

这是我的模特:

#Gallery Model
class Gallery < ActiveRecord::Base
 has_many :gallery_photos
 validates :name, presence: true
end

#GalleryPhoto Model
class GalleryPhoto < ActiveRecord::Base
 belongs_to :gallery
 has_attached_file :photo, :styles => { :small => "150x150>" },
              :url  => "/assets/gallery_photos/:id/:style/:basename.:extension",
              :path => ":rails_root/public/assets/gallery_photos/:id/:style/:basename.:extension"

 validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/jpg', 'image/png']
end

这是我的gallery_photo控制器:

def create

@gallery_photo = GalleryPhoto.new(gallery_photo_params)
respond_to do |format|
  if @gallery_photo.save
    format.html { redirect_to galleries_galleryhome_path(id: @gallery_photo.gallery_id), notice: 'Gallery photo was successfully created.' }
    format.json { render :show, status: :created, location: @gallery_photo }
  else
    format.html { render :new }
    format.json { render json: @gallery_photo.errors, status: :unprocessable_entity }
  end
end
end

private
def gallery_photo_params
  params.require(:gallery_photo).permit(:gallery_id,:photo)
end

这是我的迁移文件:

class AddAttachmentPhotoToGalleryPhotos < ActiveRecord::Migration
 def self.up
  change_table :gallery_photos do |t|
   t.attachment :photo
  end
 end

 def self.down
   remove_attachment :gallery_photos, :photo
 end
end

在我看来,我写了以下一行来附加图片:

<%= form_for @gallery_photo,html: { multipart: true},url: gallery_photos_path,method: :post do |f| %>
  <div>
   <%= f.file_field :photo, multiple: true %>
  </div>
  <div class="actions">
   <%= f.submit %>
  </div>
<% end %>

这是GalleryPhoto表的字段:

class CreateGalleryPhotos < ActiveRecord::Migration
  def change
    create_table :gallery_photos do |t|
      t.references :gallery, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

附件字段由我上面提到的迁移文件添加。

2 个答案:

答案 0 :(得分:0)

我认为您忘记将与附件相关的属性添加到 gallery_photos

add_column :photos, :photo_file_name,:string
add_column :photos, :photo_content_type,:string
add_column :photos, :photo_file_size,:integer
add_column :photos, :photo_created_at,:datetime

答案 1 :(得分:0)

这行代码失败

@gallery_photo = GalleryPhoto.new(gallery_photo_params)

因为表单帖子返回的gallery_photo_params值类似于

{
    gallery_photo: { photo: [file1, file2,...] }
}

如果要将多张照片更新为图库。你需要更新画廊而不是画廊照片。

<%= form_for @gallery do |f| %>
  <div>
   <%= f.file_field :gallery_photos, multiple: true %>
  </div>
  <div class="actions">
   <%= f.submit %>
  </div>
<% end %>

并在您的图库控制器中

def update
  if @gallery.update(gallery_params)

    redirect_to some_path
  else
    render :edit
  end
end

如果您想要创建包含多张照片的图库,情况也一样。