ruby-on-rails - 在 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 表单中的产品名称旁边显示其中一张产品照片的缩略图?
解决方案
如: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 文件中设置了新标签标签的样式。
推荐阅读
- python-3.x - 在散景渲染后是否可以将边缘/节点信息返回给 python?
- c++ - 如何找出字符串是否只有数字,没有字母
- c# - 有没有办法在 WebAPI 中不引用 EntityFramework?
- angular - 到前一个组件的角度路由不起作用
- cpu - 操作系统中的上下文切换
- bixby - 如何让 bixby 使用 app-launch 打开谷歌地图?
- react-native - 有没有办法在 Firebird 数据库和 React-Native 应用程序之间建立连接?
- java - Java EE 7 - 如何从容器内部启动事务?
- python-3.x - 我的卷积网络损失没有改变,并且在整个训练过程中保持停滞。如何解决这个问题?
- graphql - 使用 GraphQL 检索包含具有不同模式的对象数组的对象