Labels for radio buttons in rails form

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

My question is similar to this one but for a Rails app.

I have a form with some radio buttons, and would like to associate labels with them. The label form helper only takes a form field as a parameter, but in this case I have multiple radio buttons for a single form field. The only way I see to do it is to manually create a label, hard coding the ID that is auto generated for the radio button. Does anyone know of a better way to do it?

For example:

           true %> Email      SMS  

This generates something like:

  Email  SMS 

What I want:

  

回答1:

    true %>            


回答2:

Passing the :value option to f.label will ensure the label tag's for attribute is the same as the id of the corresponding radio_button

        'email' %>       'sms' %>  

See ActionView::Helpers::FormHelper#label

the :value option, which is designed to target labels for radio_button tags



回答3:

If you want the object_name prefixed to any ID you should call form helpers on the form object:

- form_for(@message) do |f|   = f.label :email 

This also makes sure any submitted data is stored in memory should there be any validation errors etc.

If you can't call the form helper method on the form object, for example if you're using a tag helper (radio_button_tag etc.) you can interpolate the name using:

= radio_button_tag "#{f.object_name}[email]", @message.email 

In this case you'd need to specify the value manually to preserve any submissions.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!