In Rails, how should I implement a Status field for a Tasks app - integer or enum?

后端 未结 6 526
南笙
南笙 2021-01-30 03:24

For a Rails 3.0 Todo app, I have a Tasks model with a Status field. What\'s the best way to store the Status field data (field type) and still display a human-r

6条回答
  •  太阳男子
    2021-01-30 03:51

    Using integer to store the status is a good idea. Nonetheless, I think the code provided by the accepted answer is not elegant since it pollutes the whole model class just because of an attribute.

    My suggestion is overriding the attribute getter:

    def status
      {
        0 => "active",
        1 => "inactive"
      }[read_attribute(:status)] # use the read_attribute method to prevent infinite loop.
    end
    

    The logic of transforming the integer into a string will be only in this getter method, so you don't need to make the class dirty.

提交回复
热议问题