views:

181

answers:

1

I create variables model which have two attributes name and value for saving any options in my site. What I want to know is do I need any special method like serialize to make rails recognize data type after it read or before it write to db ?

I try it without serialize :value but only data type work are array hash and string the others don't.and every things work fine, but it really is ? if yes why do rails have this serialize method.

This is my code

class CreateVariables < ActiveRecord::Migration
  def self.up
    create_table :variables do |t|
      t.string :name
      t.text :value

      t.timestamps
    end

    add_index :variables, :name, :unique => true
  end

  def self.down
    drop_table :variables
  end
end

class Variable < ActiveRecord::Base


  validates_uniqueness_of :name
  validates_presence_of :name, :value

end
A: 

Serialize is only needed when storing an object in the database as an attribute on an ActiveRecord model.

From your vague description of your variables table, serialize should not be necessary. You will not need to serialize attributes if they store nicely into any of the standard database column types, such as String, Fixnum, Boolean or any of their sub classes. If the values in your name/value pairs are any more complex than that, you will need to serialize. For example, of values that are Arrays, Hashes and custom objects will need to be serialized.

Once specified with the serialize method, you don't have to do anything else.

EmFi
From what I try, I can't retrieve int and float as its type. Using Variable.create(:name => 'int', :value => 123) and Variable.find_by_name('int').value. It return "123" not 123. After that I tried serialize :value, but nothing work both complex and not complex
art
The problem there is that your database field isn't an number type(Integer/Decimal/Float/etc). Serializing won't do any thing if you're not dealing with a data structure. You may also want to consider providing an object argument to ActiveRecord::Base#Serialzie so that things are always interpreted the same way.
EmFi
I used database field as text with intention to use it as variable holder whether int, float, string, array, hash. At first I think serialize would be like serialize and unserialize in php, but not. I have tried Marshal, but sqlite show an error "unrecognized token". Don't know what to do.
art
I know a fair bit about ActiveRecord, but what you're trying to do is a little beyond my skill level. At this time I don't think I can help any more on this topic.
EmFi
Thanks anyway :)
art