Rails check_box_tag set checked with condition value

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


Reference: http://stackoverflow.com/questions/11796629/rails-check-box-tag-set-checked-with-default-value#_=_



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s