Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
整个集合的ActiveRecord映射计数,然后将该查询映射到SQL_Sql_Ruby On Rails_Activerecord - Fatal编程技术网

整个集合的ActiveRecord映射计数,然后将该查询映射到SQL

整个集合的ActiveRecord映射计数,然后将该查询映射到SQL,sql,ruby-on-rails,activerecord,Sql,Ruby On Rails,Activerecord,如何用SQL编写此查询 a = Brand.find(1).publications.map(&:component_id) Hash[a.group_by(&:itself).map {|k, v| [Component.find(k).name, v.size] }] => {"title one"=>1, "something"=>1, "continue"=>1} 显然,我不能在Ennumerable上调用。\u sql。到目前为止,我已经写了

如何用SQL编写此查询

a = Brand.find(1).publications.map(&:component_id)
Hash[a.group_by(&:itself).map {|k, v| [Component.find(k).name, v.size] }]

=> {"title one"=>1, "something"=>1, "continue"=>1}
显然,我不能在
Ennumerable
上调用
。\u sql
。到目前为止,我已经写了这篇文章,但它似乎在计算发生次数以外的其他事情:

SELECT c.name, c.id, COUNT(p.component_id)
FROM publications p
INNER JOIN components c 
ON c.id = p.component_id 
INNER JOIN brands_components bc
ON bc.brand_id IN (1)
GROUP BY 1, 2
这会得到错误的数字(即太多相同的数字):

模型关联如下所示:

class Brand < ActiveRecord::Base
  has_many :documents
  has_many :publications, through: :users
  has_many :users
end

class User < ActiveRecord::Base
  has_many :documents, dependent: :destroy
  has_many :publications, through: :documents, dependent: :destroy
end

class Document < ActiveRecord::Base
  belongs_to :user
  belongs_to :brand

  has_many :components, through: :publications
  has_many :publications, dependent: :destroy
end

class Publication < ActiveRecord::Base
  belongs_to :document
  belongs_to :component
end

class Component < ActiveRecord::Base
  has_many :publications
  has_many :documents, through: :publications
end
class品牌
我想返回由SQL中的
品牌
过滤的
出版物
组件id
的出现次数。

我已经解决了我的问题:

SELECT c.name, COUNT(p.component_id)
FROM publications p
INNER JOIN components c 
ON c.id = p.component_id 
INNER JOIN brands_components bc
ON c.id = bc.component_id
AND bc.brand_id IN (1)
GROUP BY 1

我忘了匹配:
c.id=bc.component\u id
。可能会帮助某人。

因此
品牌
有很多
用户
用户
有很多
文档
文档
有很多
组件
。你想对一个品牌的所有组件进行计数吗?请发布模型关系,并说明你需要的数据是什么,backCode已经更新。
SELECT c.name, COUNT(p.component_id)
FROM publications p
INNER JOIN components c 
ON c.id = p.component_id 
INNER JOIN brands_components bc
ON c.id = bc.component_id
AND bc.brand_id IN (1)
GROUP BY 1