I am trying to create the for attribute for a label in a nested form (Using nested_form). Is there a way to get the id of a corresponding f.checkbox?
HAML:
= label_tag '???', "Set as On", class: primary_btn
= f.check_box :is_on
Additional Information:
The current Model structure is like Post has many Images with field is_on
So I would like to create a nested field group like:
<label class="primary_btn" for="post_images_attributes_0_is_on">Set as primary</label>
<input id="post_images_attributes_0_is_on" name="post[images_attributes][0][is_on]" style="display:none;" type="checkbox" value="1">
The trick is to use
fields_for. It gives you a "scoped" form builder instance which creates inputs for the nested fields.However your solution has some real gotchas:
post.imagesto ensure that only one image has theis_onflag.primary_image = post.images.where(is_on: true)A better solution is create a special relation to the primary image on Post.
This would store the primary image as an integer in
posts.primary_image_idinstead of as a boolean flag onimages.We can use
collection_selectto get select tag to display the primary image attribute.This admittedly is not really optimal from a user experience perspective. A solution which requires javascript would be to have a hidden field for
:primary_imageand update its value when the user clicks the checkbox. If you are unsure how to do this please create a new question since its out of the scope of your original question.