如何使用rails 4集合并通过枚举确定对象计数?

时间:2014-11-05 00:11:57

标签: ruby-on-rails ruby-on-rails-4 enums

我有一个Rails 4应用程序,其中一个用户拥有Sales_Opportunity,每个Sales_Opportunity可以有一个" pipeline_status"目前作为枚举实现。这工作正常,但现在我正在尝试创建一个用户显示,以图形方式显示每个这些pipeline_status(一系列的V形,从#34;前景"到#34; closed_won&# 34;)我希望在每个V形图标上显示一个徽章,显示用户在每个pipeline_status中的机会数量。

我试图在rails中使用count方法,并传递一些条件 - 但是虽然这告诉我用户有多少Sales_Opportunities(总计),但它不会接受条件参数并根据我通过了。任何人都可以帮助或指向一个可以帮助我学习正确使用方法的资源吗?

Sales_Opportunity.rb:

class SalesOpportunity < ActiveRecord::Base
default_scope { order('close_date ASC') }
belongs_to :user
belongs_to :company
has_many :timeline_events, dependent: :destroy
has_many :swots, dependent: :destroy
validates :close_date, presence: true
validates :user_id, presence: true
validates :company_id, presence: true
validates :opportunity_name, presence: true
enum pipeline_status: [ :prospect, :qualifying, :demonstrating, :negotiating, :closed_won, :closed_lost, :dormant ]
end

我目前尝试在&#34;用户信息中心&#34;:

上展示这些内容
<div class="container-fluid">
  <div class="row">
    <div class="col-lg-12">
      <div id="chevrons">
        <ul>
          <li><a href="#1">Prospect
              <span class="badge"><%= @user.sales_opportunities.count(:conditions => ":pipeline_status == 0") %></span>
          </a></li>
          <li><a href="#2">Qualifying
              <span class="badge"><%= @user.sales_opportunities.count(:conditions => ":pipeline_status == 1") %></span>
          </a></li>
          <li><a href="#3">Demonstrating
              <span class="badge"><%= @user.sales_opportunities.count(:conditions => ":pipeline_status == 2") %></span>
          </a></li>
          <li><a href="#4">Negotiating
            <span class="badge"><%= @user.sales_opportunities.count(:conditions => ":pipeline_status == 3") %></span>
          </a></li>
          <li><a href="#5">Closed
            <span class="badge", id="won"><%= @user.sales_opportunities.count(:conditions => ":pipeline_status == 4") %></span>
            <span class="badge", id="lost"><%= @user.sales_opportunities.count(:conditions => ":pipeline_status == 5") %></span>
          </a></li>
          <li id="dormant"><a href="#1">Dormant
          <span class="badge"><%= @user.sales_opportunities.count(:conditions => ":pipeline_status == 6") %></span>
        </a></li>
    </ul>
  </div>
</div>

编辑:为清楚起见,此页面的当前结果是显示每个徽章的编号。我只给了这个用户一个sales_opportunity(枚举:&#34; Prospect&#34;),它应该注册&#34; 1&#34;对于&#34;展望&#34;雪佛龙徽章和&#34; 0&#34;所有其他雪佛龙徽章都可以按照我的预期工作。

我想知道是否需要在Sales_Opportunity代码中或者在帮助器方法中将此逻辑提取为单独的方法调用,但是我认为必须有一些方法可以根据标准的Rails计数功能使其工作。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

count不再接受条件参数。请改用where。例如:

替换:

@user.sales_opportunities.count(:conditions => ":pipeline_status == 1")

使用:

@user.sales_opportunities.where(pipeline_status: 1).count