我正在用Paperclip爲Ruby on Rails編寫一些圖像上傳代碼,並且我有一個工作解決方案,但它非常黑客,所以我非常感謝關於如何更好地實現它。我有一個'Asset'類,其中包含關於上傳圖像的信息,包括Paperclip附件和封裝尺寸信息的'Generator'類。每個「項目」有多個資產和發電機;所有資產應根據每個發電機指定的尺寸進行調整;因此每個項目都有一定的規模,其所有資產都應該有。Ruby on Rails - 回形針和動態參數
發生器型號:
class Generator < ActiveRecord::Base
attr_accessible :height, :width
belongs_to :project
def sym
"#{self.width}x#{self.height}".to_sym
end
end
資產模型:
class Asset < ActiveRecord::Base
attr_accessible :filename,
:image # etc.
attr_accessor :generators
has_attached_file :image,
:styles => lambda { |a| a.instance.styles }
belongs_to :project
# this is utterly horrendous
def styles
s = {}
if @generators == nil
@generators = self.project.generators
end
@generators.each do |g|
s[g.sym] = "#{g.width}x#{g.height}"
end
s
end
end
資產控制器創建方法:
def create
@project = Project.find(params[:project_id])
@asset = Asset.new
@asset.generators = @project.generators
@asset.update_attributes(params[:asset])
@asset.project = @project
@asset.uploaded_by = current_user
respond_to do |format|
if @asset.save_(current_user)
@project.last_asset = @asset
@project.save
format.html { redirect_to project_asset_url(@asset.project, @asset), notice: 'Asset was successfully created.' }
format.json { render json: @asset, status: :created, location: @asset }
else
format.html { render action: "new" }
format.json { render json: @asset.errors, status: :unprocessable_entity }
end
end
end
我遇到的問題是雞 - 蛋的問題:新創建的資產不知道使用哪個生成器(大小規格),直到它被實例化爲止LY。我嘗試過使用@project.assets.build,但在資產獲取其項目關聯集並在我之前刪除之前,Paperclip代碼仍然被執行。
'if @generators == nil'hack是這樣的更新方法將工作,而不會在控制器中進一步黑客攻擊。
總而言之,感覺非常糟糕。任何人都可以建議如何以更明智的方式寫這個,或者甚至是採取這種方式?
在此先感謝! :)
這個問題,它的答案,幫助了很多建造相同的功能在我的應用程序。感謝大家! :) – Gediminas