views:

27

answers:

2

I want to add a has_many through association to a activerecord model class for each symbol in an array. for example

PeopleOrganisation::ROLES.each do |role|
    has_many role.to_s.pluralize.to_sym, :through => :people_organisations, :source => :person,
      :conditions => "people_organisations.role = '#{role.to_s}'" do
      def << (object)
        PeopleOrganisation.send(:with_scope, :create => {:role => **role**}) { self.concat object }
      end
      end
  end

everything works fine except for the reference to the role variable inside the method def. This is because the method def is not a closure. Is there a way of achieving what I want?

A: 

Instead of defining method using def you can try define_method method:

PeopleOrganisation::ROLES.each do |role|
  has_many role.to_s.pluralize.to_sym, :through => :people_organisations, :source => :person,
           :conditions => "people_organisations.role = '#{role.to_s}'" do
    define_method(:<<) do |object|
      PeopleOrganisation.send(:with_scope, :create => {:role => role}) { self.concat object }
    end
  end
end
lest
perfect, thanks for keeping my code DRY
A: 

Try this:

PeopleOrganisation::ROLES.each do |role|
  has_many(role.to_s.pluralize.to_sym, 
             :through => :people_organisations, :source => :person,
             :conditions => ["people_organisations.role = ?", role]
  ) do
    define_method("<<") do |object|
      PeopleOrganisation.send(:with_scope, :create => {:role => role}) { 
        self.concat object 
      }
    end
  end
end
KandadaBoggu
perfect, thanks for keeping my code DRY