AlexQuezada
AlexQuezada

Reputation: 143

How to setup checkbox on index view based on model attribute?

I have a model product and it has an attribute called active, in the index im showing the full list of products.

So, what I want to do is to show the attribute active as a checkbox checked or unchecked based on the product active attribute,

I´ve been trying with check_box_tag but it doesnt work, it shows the checkboxes always checked, here is my code line for checkboxes.

I´m using smallint on db with postgres, saving just 1 or 0:

  <%= check_box_tag "Active", product.active, product.active,disabled: true %>

Upvotes: 2

Views: 388

Answers (2)

widjajayd
widjajayd

Reputation: 6253

if you using bootstrap 3 you can use this idea

setup in product.rb one method like this

  def active_status
    if product.active
      "glyphicon glyphicon-ok text-success"
    else
      "glyphicon glyphicon-minus text-danger"
    end
  end

and in your show.html.erb you can output as follow

<i class='<%= product.active_status %>'></i>

this will showing green green check mark if product.active equal to true and minus sign if false

Upvotes: 1

Ryan Workman
Ryan Workman

Reputation: 51

The cheack_box_tag method in Rails can take a few different arguments. According to APIDock (check_box_tag 'eula', 'accepted', false, disabled: true) the argument that determines if the checkbox is marked is the third argument. It looks like you're passing product.active into that argument. According to your question, you say it's return a 1 or a 0, which are both objects and interpreted as True in Ruby. I'd suggest a ternary statement to get around that mess.

<%= check_box_tag "Active", product.active, (product.active == 1 ? true : false), disabled: true %>

Upvotes: 0

Related Questions