【问题标题】:Ruby/Rails - How can I add items to an object with each loop iterationRuby/Rails - 如何在每次循环迭代时向对象添加项目
【发布时间】:2011-01-14 07:35:37
【问题描述】:

我正在尝试进一步了解 ruby​​ .....

如果我有一个对象

 @Trees =  Tree.find( :all )

然后创建一个循环,为我找到的每棵树添加一些苹果...

 for tree in @trees   
     @apples = Apple.where(:tree_location = > tree.id )
 end

如何将循环的每次迭代中找到的额外苹果添加到初始对象@apples?

我试过了

    @apples = @apples + Apple.where(:tree_location = > tree.id )

但收到错误“无法将 Apple 转换为数组”

感谢您的帮助....

【问题讨论】:

    标签: ruby ruby-on-rails-3 for-loop


    【解决方案1】:

    如果您想要所有树上的所有苹果,您应该查看以下查询:

    @trees =  Tree.find( :all )
    @apples = Apple.where(:tree_location => trees.map(&:id))
    

    生成以下sql

    select * from apples where tree_location in (... tree ids ...);
    

    它会给你所有属于树的苹果,并且只需要两次查询而不是 n+1

    【讨论】:

      【解决方案2】:

      不太确定我明白你的意思,但是......

      trees =  Tree.find( :all )
      apples = []
      trees.each do |tree|
        apples << Apple.where(:tree_location = > tree.id ).to_a
      end
      
      apples = apples.flatten.uniq!
      
      puts apples.inspect
      

      【讨论】:

      • flatten 是因为他在Apple.where 上做to_a,产生了数组数组。它不如其他解决方案有效。
      【解决方案3】:

      你可以在末尾加上“all”:

      @apples = @apples + Apple.where(:tree_location = > tree.id ).all
      

      【讨论】:

        猜你喜欢
        • 2011-06-09
        • 2017-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-06
        • 2018-05-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多