问题
I'm trying to use a radio_button_tag
to generate a radio-button tag like:
<input type="radio" ... required>
in order to add form validation (I'm using Foundation and trying to make use of the Abide library). The closest I can get is:
radio_button_tag 'my_radio', ... , required: ''
# => <input type="radio" ... required="required">
This seems to be good enough for Abide to work, but is there a way I can get what I want out of the Rails helper? I've tried required: true
in place of required: ''
but it behaves the same.
回答1:
As you can see here: https://github.com/rails/rails/blob/4de8851289077239ecc91473bdba30f8cf6727bb/actionview/lib/action_view/helpers/tag_helper.rb#L149
Rails just looks for the presence of a value with "if value". A blank string is considered a value since it isn't nil and that is what triggers rails to include that "required='required'" attribute.
Does Abide really need the tag to be blank? It looks like it may just be checking for the presence of the "required" attribute so it may not care if the attribute has a value or not.
回答2:
There wasn't a literal answer to copy/paste so I am providing one.
<%= radio_button_tag(:model_id, model.id, false, required: 'required') %>
来源:https://stackoverflow.com/questions/24866912/rails-how-to-add-an-empty-required-attribute-to-a-radio-button-tag