I'm creating simple form in rails for create a new account, each account must has their icon. but I don't know how can I use the icon association to add in the input_html their respective icon image.
I'm trying to display the list of icons, the Icons has an url and their has a foreign key in the accounts, so I'm using this:
<%= 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 %>
but in this code I'm adding the background to the label, and I wanna have the label empty and use the background image in the input.
If I use this I can add the bg image to the imput but i don't know how can I replace the 'saving_icon' for the icon.url, because I alerady try with lambda but still not working
<%= 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')});"
}
%>
any tip for achive this it'll be well received, thank you!
I'm not very well versed in simple_form, but I can give some pointers.
Unfortunately, I can't see anywhere saying that the input_html
argument (or similar) can take a lambda in the same way as label_method
or value_method
.
However, I was able to find a GitHub issue for simple_form in relation to this - see this comment in particular. It looks like HTML attributes can be included as the third array element within the collection
argument. So you might be able to use something like this (very much untested):
f.association :icon,
# ...
collection: Icon.all.map do |icon|
[
icon.name,
icon.id,
{ style: "background-image: url(#{cl_image_path(icon.url)})" },
]
end
Alternatively, defining a custom input looks to give you all the flexibility you'd need.
Or, with such customisation of the HTML you want generated, it might just be simpler to produce the desired HTML yourself, skipping using simple_form for this set of radio buttons.
I see you've added the tag ruby-on-rails-3
. Rails 3 was End-of-Life'd
several years ago, and so is not receiving security updates. If you are indeed still running Rails 3, I strongly advise you to upgrade.