如何计算满足关联模型中条件的记录?

时间:2012-02-18 03:22:29

标签: ruby-on-rails ruby-on-rails-3 rails-models

好的,我得到的是两个型号......

Jiraissue:

class Jiraissue < ActiveRecord::Base
  # JIRA uses a singular table name for this model
  set_table_name 'jiraissue'
  has_one :severity
end

严重性:

class Severity < ActiveRecord::Base
  belongs_to :jiraissue
end

我要做的是得到jiraissue.severity =“S1”的所有Jiraissues的数量

现在事实证明jiraissue表有一个优先级列,所以我可以在模型中提取这个技巧......

Jiraissue:

class Jiraissue < ActiveRecord::Base
  # JIRA uses a singular table name for this model
  set_table_name 'jiraissue'
  has_one :severity

  def self.count_priority(priority)
    where("PRIORITY = ?",priority).count()
  end

end

然后在视图中执行类似......

的操作
<%= (1..4).map {
  |priority| Jiraissue.biit.bugs.recent.count_priority(priority)
  }.inspect %>

如何为Jiraissue做类似的事情来获取count_severity方法?

这不起作用(我也不期望)......

  def self.count_severity(severity)
    where("severity = ?",severity).count()
  end

但我完全糊涂了。

2 个答案:

答案 0 :(得分:0)

Jiraissue.joins(:severities).where(:severities => {:severity => "S1"}).count

答案 1 :(得分:0)

<强>模型

def self.count_priority(priority)
  where("PRIORITY = ?",priority).size
end

<强>控制器

def index
  @jiraissues = Jiraissue.count_priority('S1')
end

不起作用吗?