Dynamically adding custom fields to a model
I have a model called List which has many records:
class List
has_many :records
end
class Record
end
There are 2 constant fields in the table record: name, email address.
In addition to these 2 fields, a record can have "n" custom fields for each list.
For example: for list1, I add address (text), dob (date) as custom fields. Then, by adding entries to the list, each entry can have values for address and dob.
Is there any ActiveRecord plugin that provides this type of functionality?
Or could you share your thoughts on how to model this?
Thanks in advance,
Pankai
a source to share
If your custom fields don't have to be real database columns, you can use serialize : http://railsapi.com/doc/rails-v2.3.5/classes/ActiveRecord/Base.html#M000924 You would use it like:
class Record < ActiveRecord::Base
serialize :custom_fields, Hash
end
r = Record.create :custom_fields => {:name => 'John Doe', :birth_date => Date.new(1970,1,1)}
r.custom_fields[:name]
# => 'John Doe'
r.custom_fields[:birth_date]
# => #<Date: 4881175/2,0,2299161>
Pro : easy to use
Kon : since custom fields are not db columns, you cannot find records in the database based on their values (eg Record.find_by_name ("John Doe") doesn't work)
a source to share
Maybe this? has_magic_columns . I haven't tested it myself, but it looks like it can do what you need.
a source to share