首页 > 解决方案 > 在 activeadmin 表单中的复选框标签旁边添加图像

问题描述

我在 rails 应用程序中使用 gem 'activeadmin', '~> 1.3'。我在两个模型之间有这些关系:

class Offer < ApplicationRecord
  has_many :products
end
class Product < ApplicationRecord
  belongs_to :offer, required: false
  has_attachments :photos, maximum: 4, dependent: :destroy
end

我可以通过这种方式访问​​产品的第一张照片:@product.photos[0]@product.photos[0].path

在 admin/offer.rb 中,用于选择属于该优惠的产品的复选框是使用以下内容构建的:

f.input :products, as: :check_boxes

这会呈现一个带有产品名称作为标签的复选框列表。现在我想用旁边的一个产品照片的缩略图来丰富这个标签。

构建复选框时,我未能遍历“:products”。我想添加一个这样的 html 标记 : span img(src: "product_image_path"),就像我在 activeadmin 中显示产品页面时所做的那样。

我检查了 formtastic 文档,只发现了这个自定义选项::collection => Product.pluck(:name, :id)。这使我只能更改标签中的文本,但不提供添加图像的方法。

如何在 activeadmin 表单中的产品名称旁边显示其中一张产品照片的缩略图?

标签: ruby-on-railsactiveadminformtastic

解决方案


如:formtastic 文档中所述,您可以自定义现有输入。因此,我在 app/inputs/checkbox_image_input.rb 中创建了一个 checkbox_image 输入:

class CheckboxImageInput < Formtastic::Inputs::CheckBoxesInput
  include CloudinaryHelper

  def choice_html(choice)
    template.content_tag(
    :label,
    img_tag(choice) + checkbox_input(choice) + choice_label(choice),
    label_html_options.merge(:for => choice_input_dom_id(choice), :class => 
    "input_with_thumbnail"))
 end

  def img_tag(choice)
    cl_image_tag(Product.find(choice[1]).photos[0].path, :width=>30, 
    :crop=>"scale")
  end
end

我使用 cloudinary 作为图像存储服务,您可以根据自己的更新 img_tag(choice)。然后您可以使用 admin/model.rb 中的新输入,格式为:

f.input :products, as: :checkbox_image, :collection => product_selection

最终,我使用 input_with_thumbnail 类在我的 active_admin_custom_css.css 文件中设置了新标签标签的样式。


推荐阅读