Dynamic Rail Attributes

I would like to have a number of dynamic attributes for the user model, for example, phone, address, zipcode, etc., but I would not want to add them to the database. Therefore, I created a separate table called UserDetailsfor the key-value pairs and belongs_to :User.

Is there a way to somehow do something dynamic, like this one user.phone = "888 888 8888", which essentially will call a function that does:

UserDetail.create(:user => user, :key => "phone", :val => "888 888 8888")

and then have the appropriate recipient:

def phone  
    UserDetail.find_by_user_id_and_key(user,key).val
end

All this, but for a number of attributes provided as a phone, zip code, address, etc., without the arbitrary addition of a ton of getters and setters?

+5
source share
2 answers

, - : ( )

class User < ActiveRecord:Base
  define_property "phone"
  define_property "other"
  #etc, you get the idea


  def self.define_property(name)
    define_method(name.to_sym) do
      UserDetail.find_by_user_id_and_key(id,name).val
    end
    define_method("#{name}=".to_sym) do |value|
      existing_property = UserDetail.find_by_user_id_and_key(id,name)
      if(existing_property)
        existing_property.val = value
        existing_property.save
      else
        new_prop = UserDetail.new
        new_prop.user_id = id
        new_prop.key = name
        new_prop.val = value
        new_prop.save
      end
    end
  end
+2

:

class User < ActiveRecord:Base
  has_one :user_detail
  delegate :phone, :other, :to => :user_detail
end

user.phone = '888 888 888' user.phone. Rails , .

+8

All Articles