我正在使用Paperclip上传多个项目图片。我按照本教程的一些内容http://sleekd.com/general/adding-multiple-images-to-a-rails-model-with-paperclip/ 我的模特是:
item.rb的
has_many :item_images, :dependent => :destroy
accepts_nested_attributes_for :item_images, :reject_if => lambda { |l| l['item_image'].nil? }
ItemImage.rb
class ItemImage < ActiveRecord::Base
belongs_to :item
belongs_to :user
#for image. Paperclip following Bootstrap sizes.
has_attached_file :image,
:styles => { :large => ["330x230>",:png], :medium => ["210x150>",:png], :small => ["90x90>",:png], :thumb => ["32x32>", :png] },
:default_url => '/images/missing_image_:style.png',
:storage => :s3,
:bucket => 'iscomp',
:s3_credentials => "#{RAILS_ROOT}/config/amazon_s3.yml",
:path => "iscomp/:attachment/:style/:id.:extension"
validates_attachment_presence :image
validates_attachment_size :image, :less_than => 5.megabytes
end
我的问题是因为图像存储在第二个模型上,所以当@ item.item_image上没有图像/记录时,我无法访问默认的空白图像。如果我直接在@item上使用过paperclip,Paperclip将为我返回默认图像。
如果我不想在每次调用缩略图时都不断添加if / unless语句,那么最好的方法是什么?
答案 0 :(得分:0)
我不知道你是否正在寻找一种优雅的方式,但我的方法是创建一个默认图像,如果@ item.item_image返回空白,我会显示默认的空白图像。我没有使用paperclip default。
答案 1 :(得分:0)
您可以通过以下方式解决此问题:
在迁移中添加itemimage_count
def self.up
add_column :item, :itemimage_count, :integer, :default => 0
Item.reset_column_information
Item.all.each do |item|
item.update_attribute :itemimage_count, item.itemimages.length
end
end
def self.down
remove_column :item, :itemimage_count
end
end
然后,这会将多个ItemImages与每个项目相关联。您可以在视图,控制器和模型中访问此计数器。
如果你想要漂亮,可以在模型中设置范围条件。
item.rb的
scope :list, :conditions => ["itemimages_count >= 0"]
Item_controller
@itemimages = Item.list
我个人会在你的观点中使用一组if else语句,只要你想显示图像,只需调用部分语句。
if Item.itemimages_count == 0
#show this image
end
#code that displays an Item's image
#show the image in itemimages
我希望这有助于某人。