Forum: Ruby on Rails DRY AR models

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Pierre-Alexandre M. (Guest)
on 2007-03-07 01:53
(Received via mailing list)

I need an advice ;)

Assuming you have a form like:
Father's kids: <%= in_place_editor_field %>
Mother's kids: <%= in_place_editor_field %>

with just a Person model.

You want your customers to write directly:
Father's kids: mike,dave,chad
Mother's kids: david

I think a proper method to do this is:
 1/ Create Father < Person and Mother < Person models
 2/ Create in those models accessors:
  def kids=(value)
    value.split(',').each do |kid|
      child = Person.find_by_name(kid)
      child.nil? Person.create(:name => kid, :parent_id => :
child.parent_id =

  def kids
    # find etc.
 3/ Simply put @father_kids & @mother_kids in your controller

But that's not DRY at all. So to improve this code, we could simply put
in a 'lib/people.rb' file:
  @people = ['father','mother']
  @people.each do |parent|
  # define_method("#{kids=}") etc.

and require the file in our models.
Actually, it's what I have done in my project, and it works (hope you
don't find this ugly :)).

My question is: that not DRY enough. I mean, if you want to add an:
Sister's kids: etc.
You'll need to generate a model, require the same files etc.

So, is it 'recommended' ('authorized', is it proper code?) to add
Classes on-the-file to AR? I mean, not to
write Father.rb, Mother.rb but just create a load_classes.rb (required
in boot.rb I suppose) which define_class (oops, returns me a define_class (WIN32COMGen)<--
?!) after AR has reconized the Person model.

Actually, you can do it with a rake file but you need to regenerate it
whenever you change your @people array.

Thanks for your replies.

| Pierre-Alexandre M. |
| email : removed_email_address@domain.invalid |
This topic is locked and can not be replied to.