如何将背景图像添加到 simple_form_for - Rails 中的输入

问题描述 投票:0回答:1

我在 rails 中创建简单的表单来创建一个新帐户,每个帐户都必须有自己的图标。但我不知道如何使用图标关联在 input_html 中添加它们各自的图标图像。

我正在尝试显示图标列表,图标有一个 url 并且它们在帐户中有一个外键,所以我正在使用这个:

<%= simple_form_for [@account], data: { account_card_target: "form" } do |f| %>
        <div class="form-inputs">
          <%= f.input :account_name %>
          <%= f.input :account_type,
                      collection: ['***', '***', '***', '***'],
                      prompt: "Select a type" %>
          <%= f.input :balance %>
          <%= f.input :account_number  %>
          <%= f.association :icon,
                as: :radio_buttons,
                label_method: ->(icon) { "<label class='icon-radio-label' for='my-input' style='background-image: url(#{cl_image_path(icon.url)})'></label>".html_safe },
                value_method: :id,
                input_html: { class: 'my-input', id: 'my-input' }
        %>
        </div>
        <div class="form-actions">
          <%= f.button :submit %>
        </div>
<% end %>

但是在这段代码中,我将背景添加到标签中,我想让标签为空,并在输入中使用背景图像。

如果我使用它,我可以将 bg 图像添加到输入中,但我不知道如何替换 icon.url 的“saving_icon”,因为我已经尝试使用 lambda 但仍然无法正常工作

<%= f.association :icon,
        as: :radio_buttons,
        label_method: ->(icon) { " " },
        value_method: :id,
        input_html: {
          class: "icon-radio",
          style: "background-image: url(#{cl_image_path('saving_icon')});"
        }
%>

实现此目标的任何提示都会受到欢迎,谢谢!

ruby ruby-on-rails-3 input associations simple-form
1个回答
0
投票

我对 simple_form 不是很精通,但是我可以给一些指点。

不幸的是,我看不到任何地方说

input_html
参数(或类似的)可以像
label_method
value_method
一样采用 lambda。

但是,我能够找到与此相关的 simple_form 的 GitHub 问题 - 请特别查看此评论。看起来 HTML 属性可以作为第三个数组元素包含在

collection
参数中。所以你也许可以使用这样的东西(非常未经测试):

f.association :icon,
  # ...
  collection: Icon.all.map do |icon|
    [
      icon.name,
      icon.id,
      { style: "background-image: url(#{cl_image_path(icon.url)})",
    ]
  end

或者,定义自定义输入看起来可以为您提供所需的所有灵活性。

或者,通过自定义您想要生成的 HTML,您自己生成所需的 HTML 可能会更简单,跳过对这组单选按钮使用 simple_form。


我看到你添加了标签

ruby-on-rails-3
。 Rails 3 是 End-of-Life'd 几年前,所以没有收到安全更新。如果你确实还在运行 Rails 3,我强烈建议你升级。

© www.soinside.com 2019 - 2024. All rights reserved.