Ruby如何在count没有行时强制输出0

时间:2016-06-07 07:31:10

标签: ruby-on-rails

@counseling = Counseling.ransack(params[:q])
@counselings = @counseling.result.joins('RIGHT JOIN "subjects" ON "subjects"."id" = "counselings"."subject_id"')
@result = {}
@result[:data] = @counselings.group(row_condition).count
  

块引用

def self.create_case_sql_for_nested_tree2(foreign_key)
    modelClass = foreign_key.sub(/_id3$/, '').camelize.constantize
    @when_then_conditions = modelClass.roots.map do |o|
      o.children.map do |c|
        c.children.map do |g|
        idlist = g.self_and_descendants.pluck(:id)
        "WHEN subject_id IN(#{idlist.join(',')}) THEN #{g.id}"
        end
      end
    end
    "CASE #{@when_then_conditions.join(' ')} ELSE null END"
end

1 个答案:

答案 0 :(得分:2)

根据您的评论,您想加入CounselingSubject模型并计算subject_id。我想你可以这样做,

Counseling.joins(:subject).count(:subject_id)

如果您想放置任何条件,您可以这样做,

Counseling.joins(:subject).where("some condition").count(:subject_id)