我在 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 表单中的产品名称旁边显示其中一张产品照片的缩略图?
如: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 文件中设置了新标签标签的样式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句