How to store and compare :symbols in an ActiveRecord (Ruby on Rails)

后端 未结 7 1369
梦谈多话
梦谈多话 2021-02-05 04:51

I thought it would be good to populate a status field in an activeRecord table using constants. However, when it comes to checking if this status has a particular status, I\'m h

7条回答
  •  孤街浪徒
    2021-02-05 04:59

    If I remember well symbols in ActiveRecord are stored in yaml format, some kind of conversion must be done because there is no such thing as a symbol in relational db (which I'm aware of, at least). When you read it it's then a string which will not match your symbol and not even the string of the symbol, in fact it should be something like:

    :x # => "--- :x\n"
    

    I think this plugin can solve your problem, but I haven't used it honestly. https://github.com/zargony/activerecord_symbolize

    * EDIT *

    I leave the above because I remember that was the situation I had and I can be corrected if I'm wrong, nonetheless I'm trying this right now and the stored value (Rails 3.1.3) is a simple string with the value of the symbol, so the following should be enough.

    class Example < ActiveRecord::Base
    
      def aaa
        super.to_sym
      end
    
      def aaa=(value)
        super(value.to_sym)
        aaa
      end
    
    end
    

    This of course will force the value to always be a symbol

    ** EDIT AFTER AGES ** I think it's fine in this situation as it's clear that in the db it's a string and the logic is simple, but I strongly discourage overriding db attribute methods to add more complex logic.

提交回复
热议问题