【问题标题】:Create user defined attributes using hash - Rails使用哈希创建用户定义的属性 - Rails
【发布时间】:2012-03-02 15:10:55
【问题描述】:

我的个人资料迁移是这样的:

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 有另一个属性,我可以使用什么命令让用户添加新的详细信息?

【问题讨论】:

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


    【解决方案1】:

    对于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] }
    

    【讨论】:

    • 谢谢,Profile.new.detail = { :education => ["", true], :Town => ["Cook", false] } 这行得通,但我也可以保存 user_id连同它,因为每个用户都有单独的个人资料属性!
    • 您想让Profile 拥有多个details?每个都有Profile的属性?
    • Profile.new.detail = {education: true, user_id: @user.id},但我不知道你为什么要这么做。
    • detail 实际上是 Profile 模型中的一个属性。我希望用户能够创建自己的 info -detail 对列表。所以我将详细属性存储为哈希。
    • 然后@user.profile.build.tap {|p| p.detail = {education: true, user_id: @user.id}}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 2010-10-22
    • 1970-01-01
    • 2016-03-30
    相关资源
    最近更新 更多