Search code examples
ruby-on-railsrubysimple-form

Update a datetime attribute using a boolean input


I've got a model Story for which I'm adding a pinned_at attribute. I want a user to be able to select if the story needs to be pinned to the top of the index page but not be able to set the datetime value as it should always be the present datetime when being set.

My thinking was something like

= f.check_box :pinned_at, value: DateTime.now

But the value doesn't seem to set. Anyone have any ideas? The reason why it's not a simple boolean attribute in the first place is that I want to sort stories by whether they are pinned and their creation date. I don't think rails has a good way of sorting by a boolean?


Solution

  • Just use a datetime column together with a separate setter/getter:

    class Story < ApplicationRecord
      def pinned
        pinned_at.present?
      end
      alias_method :pinned?, :pinned
    
      def pinned=(value)
        if value
          self.pinned_at = Time.current unless pinned? 
        else
          self.pinned_at = nil
        end
      end
    end
    
    = f.check_box :pinned