如何在ActiveAdmin中显示多张图片

9

我正在使用Paperclip上传多个图像。 我也在使用Active Admin。 到目前为止,我已经能够上传多个图像并将它们关联到我的“产品”模型。 我还可以在索引页面上显示所有关联图像的名称。 但是,我无法找到如何在产品模型的展示页面中显示“所有”图像(而不仅仅是名称)。 请查看以下代码。

\app\models\product.rb

has_many :images, :dependent => :destroy
accepts_nested_attributes_for :images, :allow_destroy => true

\app\models\image.rb

belongs_to :product
has_attached_file :image, :styles => {
  :thumb=> "100x100>",
  :small  => "300x300>",
  :large => "600x600>"
    }

\app\admin\products.rb

index do
  column "Images" do |product|
    product.images.map(&:image_file_name).join("<br />").html_safe
  end
end

show do |product|
  attributes_table do
  row "Images" do
      ul do
        li do 
          image_tag(product.images.first.image.url(:small))
        end
        li do 
          image_tag(product.images.second.image.url(:small))
        end
        li do 
          image_tag(product.images.last.image.url(:small))
        end
      end
    end
  end
end

我找到了一种可行的方法,但这是非常糟糕的编程。目前,每个产品都有3个相关联的图像,并且我正在在我的展示块中使用上述代码。 请建议更好的做法。


我已经修改了代码,只有在图片存在的情况下才会显示图片。image_tag(product.images.first.image.url(:small)) if !product.images.first.nil? 然而,这段代码仍然有一个最多只能显示3张图片的限制。请建议如何更好地实现此功能。 - ansh0809
你的意思是需要展示每张图片,而不仅仅是其中的3张吗? - Fivell
1个回答

17

你的意思是需要展示每一张图片而不仅仅是其中3张吗?如果是的话,可以尝试

row "Images" do
   ul do
    product.images.each do |img|
      li do 
        image_tag(img.image.url(:small))
      end
    end
   end
end

非常感谢... 这个可行。不过,我能否以:small的方式显示第一张图像,而将其余图像作为:thumb显示? - ansh0809
是的,首先显示第一张图片,然后使用offset(1)范围并使用cycle。 - Fivell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接