乘以条件 - Rails关联的数组

时间:2014-10-23 22:09:55

标签: arrays ruby-on-rails-4 associations

我的行为属于属于属于代理商的公司的行为。

我尝试做的是在代理商级别获取属于该机构的公司的所有行为的值(在Leadactions表的列中定义)的总和。

我需要两个阵列,但我不知道如何正确总结。

模型     类Leadaction<的ActiveRecord :: Base的         belongs_to:行动     端

class Action < ActiveRecord::Base
    belongs_to :company
    has_one :leadaction
end

class Company < ActiveRecord::Base
    belongs_to :agency
    has_many :actions
    belongs_to :agency
end

class Agency < ActiveRecord::Base
    has_many :companies
    has_many :actions, through: :companies
    has_many :leadactions, through: :actions
end

控制器

class AgenciesController < ApplicationController
    def show
        @user = current_user
        @agency = @user.agency
        @companies = @agency.companies.all
        @leads = @agency.actions.where.not(leadaction_id: '').map(&:leadaction_id.to_proc)
        @leadvalues = Leadaction.all.map { |v| v.value }
    end

@leads给我一个看起来像这样的数组:[1,2,1,3,1,2,2,3,3,1,1,2,2,1,2,2]这是关联的leadaction_id列。

@leadvalues给了我:[[1,300],[2,6000],[3,300]]这是Leadaction.id和Leadaction.value

我不知道如何在第一个阵列中的任何地方获得它,它会显示300,到处都有2,它会显示6000,到处都是是一个3它显示300.所以我最终得到一个看起来像这样的数组: [300,6000,300,300,300,6000,6000,6000,300,300,300,6000,6000,300,6000,6000]

我有办法做到这一点吗?请帮助我解决这个问题至少12个小时。

1 个答案:

答案 0 :(得分:0)

以下是我现在解决的问题......虽然我确信这不是最有效的方法。

代理商管理员:

class AgenciesController < ApplicationController

def show
#market value of leads all time
    @leadvalues = @agencyleads.map { |l| Leadaction.find(l.leadaction_id) }
    @leadvalueat = @leadvalues.map { |l| l.value }
end

查看:

<%= @leadvalueat.empty? ? '$0' : number_to_currency(@leadvalueat.sum, precision: 0) %>