2010-08-26 67 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