ruby-on-railsruby-on-rails-5form-helpers

How to add form tag for a checbox attribute that is stored as a datetime in the database?


Let's say that I have a table called advertisements. I need to add a field for it so people can flag it as active or inactive. I can add a boolean field called inactive and that's a straight forward approach.

There is another approach where I can create a field inactive with datatype of datetime. This not only tells me whether an advertisement is active/no, but also tells when it was deactivated. So if the value is null, it's active and if it's a timestamp, it was deactivated at that time in the past.

The problem, however, is adding it to the form helper. For a checkbox implementation, Rails suggests following:

= f.check_box :inactive, { class: 'something' }

This works fine with the datatype as boolean in db. How do I make this work with datetime value?

Thanks!


Solution

  • Answering my own question. So with the check_box helper you can specify when a checkbox should be displayed as checked and you can also specify the value to assign when someone checks the box.

    I did this

    = f.check_box :inactive, { class: 'something', checked: f.object.inactive.present? }, f.object.inactive.nil? ? DateTime.now : f.object.inactive
    
    

    The last part DateTime.now is the value that gets assigned when a user checks the box. This way you can save a DateTime value using a checkbox implementation. The presence of value helps you determine whether the checkbox should be checked or not when you display the form.

    The only caveat with this approach is the accuracy of the value. User might submit the form after few mins/hours of opening the form. If it's important for you to capture the right value, you can use JS to assign the exact value or have the logic in the controller.