2010-08-26 58 views
0

我想通过关联将has_many添加到数组中每个符号的activerecord模型类。例如在循环内添加rails activerecord关联

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 

一切工作正常,除了方法def内的角色变量的引用。这是因为def方法不是闭包。有没有办法达到我想要的?

回答

0

试试这个:

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 
+0

完美,感谢让我的代码DRY – user432112 2010-08-27 06:41:39

0

而不是使用def定义方法,你可以尝试define_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 
+0

完美,感谢让我的代码干 – user432112 2010-08-27 06:42:01