我有一个rails应用程序。我正在使用 gem:回形针将照片上传到我的服务器。我正在尝试做的是使用 perams 哈希中的信息在服务器上创建一个文件夹结构。请参阅下面的代码。
照片控制器.rb
# POST /photos
# POST /photos.json
def create
@photo = Photo.new(params[:photo])
@photo.lat = params["photo%5Blat%5D"].to_s
@photo.lng = params["photo%5Blng%5D"].to_s
@photo.description = params[:description]
@photo.takenby = params[:takenby].to_s
@photo.save
puts "photos/create photos.inspect= #{@photo.inspect}"
end
照片.rb
class Photo < ActiveRecord::Base
attr_accessible :lat, :lng, :image
vendor = params[:description]
owner = params[:owner]
Paperclip.interpolates :prefix do |attachment, style|
"#{owner}/#{Date.today.to_s }/#{vendor}"
end
has_attached_file :image,
:path => ":prefix/:basename.:extension",
:styles => { :thumbnail => "57x57", :original => "100x100" },
:storage => :s3,
:s3_credentials => S3_CREDENTIALS
但是,我在服务器控制台上收到此错误。
Started GET "/photos?lat=37.785834&lng=-122.406417" for 127.0.0.1 at 2012-09-26
21:08:57 -0700
21:08:57 web.1 | Processing by PhotosController#index as JSON
21:08:57 web.1 | Parameters: {"lat"=>"37.785834", "lng"=>"-122.406417"}
21:08:57 web.1 | Completed 500 Internal Server Error in 4ms
21:08:57 web.1 | NameError (undefined local variable or method `params' for #<Class:0x007fb7d4fa3320>):
21:08:57 web.1 | app/models/photo.rb:23:in `<class:Photo>'
21:08:57 web.1 | app/models/photo.rb:18:in `<top (required)>'
21:08:57 web.1 | app/controllers/photos_controller.rb:14:in `index'
我需要在模型中更改什么,以便回形针以正确的文件夹结构将图像保存在服务器上?
这解决了我的问题:
photo.rb
Paperclip.interpolates :prefix do |attachment, style|
"#{attachment.instance.takenby}/#{Date.today.to_s }/#{attachment.instance.description}"
end
但这带来了一个新问题。我无法再保存不同大小的图像。我该怎么做?
您无法访问类中的参数哈希 照片通过以下方式:
vendor = params[:description]
owner = params[:owner]
描述示例:
1) 首先,创建一个 config/initializers/paperclip.rb 文件并添加以下内容:
Paperclip.interpolates :description do |attachment, style|
attachment.instance.description # or other attribute
end
2)然后,
has_attached_file :image,
:path => ":description/:basename.:extension",
:styles => { :thumbnail => "57x57", :original => "100x100" },
:storage => :s3,
:s3_credentials => S3_CREDENTIALS
3) 阅读本文以获取更多信息:
- 堆栈溢出答案 1
- 堆栈溢出答案 2
- 关于插值的文档
- 关于回形针动态路径的好文章
如果要访问它们,可以将参数作为参数传递给模型中声明的方法。
在控制器中,执行
obj.set_values(params)
在模型中,执行
def set_values(params)
self.vendor = params[:description]
self.owner = params[:owner]
end
在保存模型之前调用插值代码。
从模型中访问params
,因此这些分配将失败。
如果供应商和所有者是照片的属性,只需在创建操作中分配它们即可。您可能希望修改表单,以便可以在params[:photo]
中找到照片模型的所有值,以减少不必要的分配。
$rails g 回形针帖子照片
$ rake db:migrate
转到Post.rb并添加:
attr_accessible :p霍托 has_attached_file :p hoto, :styles => { :small => '150x150', :normal => '400x400' }, :p ath => ":rails_root/public/system/:attachment/:id/:style/:filename", :url => "/system/:attachment/:id/:style/:filename"
打开您的 _form.html.erb 并重写为:
<%= form_for (@post) do |f| %>
自:
<%= form_for @post, :html => { :multipart => true } do |f| %>
并添加这是_form:
<p>
<%= f.file_field :photo %>
</p>
在 Index.html.erb 中:
在 Show.html.erb 中: