【问题标题】:Adding an rails activerecord association within a loop在循环中添加 rails activerecord 关联
【发布时间】:2010-08-26 17:02:19
【问题描述】:

我想通过关联为数组中的每个符号添加一个 has_many 到 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 不是闭包。有没有办法实现我想要的?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord closures


    【解决方案1】:

    试试这个:

    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
    

    【讨论】:

      【解决方案2】:

      您可以尝试define_method 方法,而不是使用def 定义方法:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-15
        • 1970-01-01
        • 2021-11-30
        • 2010-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多