使用hash-Rails创建用户定义的属性

时间:2012-03-02 15:10:55

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 rails-activerecord

我的配置文件迁移如下:

class CreateProfiles < ActiveRecord::Migration
  def self.up
    create_table :profiles do |t|
      t.integer :user_id
      t.text :detail
      t.boolean :visible
      t.timestamps
      end
    add_index :profiles, :detail
  end

  def self.down
    drop_table :profiles
  end
end

我有User has_one ProfileProfile belongs_to User关系。

现在,我想将配置文件详细信息存储为序列化。所以我有这样的Profile类:

class Profile < ActiveRecord::Base
  belongs_to :user
  serialize :detail, Hash
end

这是因为我希望每个用户都能够创建不同的个人资料详细信息,例如

Profile.new.detail ={:education => ["Degree", true], :Hobby => ["Music", false] }

现在,既然我有user_id有另一个属性,我可以用什么命令让用户添加新的细节?

1 个答案:

答案 0 :(得分:2)

Profile has_many Details

p = Profile.new
p.detail = []
p.detail << {:'Linked In Profile' => ["link", false]}
p.detail << {education: [...]}

Profile has_one Detail

Profile.new.detail = { :Education => ["Degree", true], :'Linked In Profile' => ["link", false] }