Rails check_box_tag set checked with condition value

In Rails, we have check_box_tag helper method to create a check box form input tag. With this helper method sometimes we have to select the check box based on the parameters, based on certain object parameter’s value and sometimes based on any variable value that already set in controller. Which can be achieve with if statement in views as following. But this is not good practice.

- if params[:search][:type] == 'Broker'
  = check_box_tag('search[:type][]', 'Broker', checked = true)
- else
  = check_box_tag('search[:type][]', 'Broker', checked = false)

There are no ways to do it directly. But the check_box_tag implementation is trivial, you can monkey patch it or create own helper.

Original implementation:

  def check_box_tag(name, value = "1", checked = false, options = {})
    html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
    html_options["checked"] = "checked" if checked
    tag :input, html_options

Which can be used in our view as following:

  - is_broker_selected = params[:search].present? && params[:search][:type].to_s.include?('Broker')
  div[class="icon-checkbox #{is_broker_selected == true ? 'grey' : ''}"]
  = check_box_tag('search[type][]', 'Broker', is_broker_selected, class: 'search_type')
  | Broker

One response to “Rails check_box_tag set checked with condition value

Leave a Reply

Your email address will not be published. Required fields are marked *

Enter Captcha Here : *

Reload Image