On Sep 27, 2:42 pm, Magnus <[email protected]> wrote:
> I have a database where information that should really have been a
> proper one-to-many relation is stored in a string. I would like to
> create a model that looks like a proper one-to-many relation and hides
> the ugly implementation details.
>
> Assuming I have a table with two columns: [UserID] and [Contacts],
> where Contacts is a string that contains multiple contacts encoded as
> a single string. Each contact has a name and a phone number. (E.g. the
> contacts string may look something like "John:555-000-9998;Tony:
> 333-222-1111;Mia:444-333-1122").
>
> I would like to create a User model that has a one-to-many relation to
> a Contact model, which has Name and Phone fields. What methods do I
> need define/override to accomplish this?

Maybe something like:

class Contact
  attr_accessor :name, :phone
  def initialize(name, phone)
    self.name, self.phone = name, phone
  end
  def to_user_string
    "#{name}:#{phone}"
  end
end

class User
  def contacts
    @contacts ||= super.split(';').map{|s| s = s.split(':');
Contact.new(:name=>s[0], :phone=>s[1])}
  end

  def add_contact(name, phone)
    contacts << Contact.new(:name=>name, :phone=>phone)
  end

  def before_save
    self[:contacts] = @contacts.map{|c| c.to_user_string}.join(';') if
@contacts
    super
  end
end

You could also look at the composition plugin (http://
sequel.rubyforge.org/rdoc-plugins/classes/Sequel/Plugins/
Composition.html), but that's more for storing a single object in a
row than multiple objects.

Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sequel-talk?hl=en.

Reply via email to