【发布时间】:2016-07-29 04:35:42
【问题描述】:
我是 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
附件字段是由我上面提到的迁移文件添加的。
【问题讨论】:
-
抛出的错误是什么?
-
它没有存储图像的属性。
-
可以放表格字段吗?
标签: ruby-on-rails ruby image upload image-gallery