Adding an rails activerecord association within a loop
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, :creat开发者_如何学Goe => {: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?
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
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
精彩评论