adding custom fields dynamically to a model
I have a model called List which has many records:
class List
has_many :records
end
class Record
end
The table Record开发者_StackOverflow has 2 permanent fields: name, email.
Besides these 2 fields, for each List a Record can have 'n' custom fields.For example: for list1 I add address(text), dob(date) as custom fields. Then while adding records to list one, each record can have values for address and dob.
Is there any ActiveRecord plugin which provides this type of functionality?
Or else could you share your thoughts on how to model this?Thanks in advance,
PankajYou should take a look in schemaless database solutions. One that i think is great is mongoDB.
There is a railscast explaining how to use it with rails. Take a look, it works great.
If your custom fields don't need to be real database columns, you could 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
Con: since the custom fields are not db columns, you can't find records in the db based on their values (e.g. Record.find_by_name('John Doe') does not work)
Maybe this? has_magic_columns. I havn't tested it myself but seems like it can do what you need.
精彩评论