在循环中添加rails activerecord关联

时间:2010-08-26 17:02:19

标签: ruby-on-rails ruby activerecord closures

我想通过关联为一个数组中的每个符号的activerecord模型类添加一个has_many。例如

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不是闭包。有没有办法达到我想要的目的?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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