开发者

Is it possible for rails to save multiple data type in same db column?

I tried to simulate variable_set and variable_get in drupal which use as site-wide variables storage. I 开发者_如何学编程tried something like this.

# == Schema Information
# Schema version: 20091212170012
#
# Table name: variables
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  value      :text
#  created_at :datetime
#  updated_at :datetime
#

class Variable < ActiveRecord::Base
  serialize :value

  validates_uniqueness_of :name
  validates_presence_of :name, :value


  def self.set(name, value)
    v = Variable.new() 
    v.name = name
    v.value = value
    v.save
  end  

  def self.get(name)
    Variable.find_by_name(name).value
  end

end

but it doesn't work.


I've found a way to do this using yaml for storing your values as encoded strings.

Since I'm not storing the "values" on the database, but their converstions to strings, I named the column encoded_value instead of value.

value will be a "decoder-getter" method, transforming the yaml values to their correct types.

class Variable < ActiveRecord::Base
  validates_uniqueness_of :name

  validates_presence_of :name, :encoded_value #change in name

  def self.set(name, value)
    v = Variable.find_or_create_by_name(name) #this allows updates. name is set.
    v.encoded_value = value.to_yaml #transform into yaml
    v.save
  end  

  def self.get(name)
    Variable.find_by_name(name).value
  end

  def value() #new method
    return YAML.parse(self.encoded_value).transform
  end

end

This should return integers, dates, datetimes, etc correctly (not only raw strings). In addition, it should support Arrays and Hashes, as well as any other instances that correctly define to_yaml.


I have the following in one of my applications :

class Configure < ActiveRecord::Base
    def self.get(name)
        value = self.find_by_key name
        return value.value unless value.nil?
        return ''
    end

    def self.set(name, value)
        elem= self.find_by_key name

        if elem.nil?
            #We add a new element
            elem = Configure.new
            elem.key = name
            elem.value = value
            elem.save!
        else
            #We update the element
            elem.update_attribute(:value, value)
        end
        return elem.value
    end
end

Which is apparently what you're looking for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜