Ruby on rails Rails有许多直通、分组和求和数据

Ruby on rails Rails有许多直通、分组和求和数据,ruby-on-rails,postgresql,ruby-on-rails-4,associations,grouping,Ruby On Rails,Postgresql,Ruby On Rails 4,Associations,Grouping,我不知道如何通过关系将数据分组并获取数据。我当前的模型如下所示: class User < ActiveRecord::Base has_many :project_items, dependent: :destroy has_many :ingredients, through: :project_items end class Ingredient < ActiveRecord::Base has_many :project_items end class

我不知道如何通过关系将数据分组并获取数据。我当前的模型如下所示:

class User < ActiveRecord::Base
   has_many :project_items, dependent: :destroy
   has_many :ingredients, through: :project_items
end

class Ingredient < ActiveRecord::Base
   has_many :project_items
end

class ProjectItem
   belongs_to :user
   belongs_to :ingredient
end
它指向当前仅输出名称和数量以及创建时间的_project_item partial

<li>
    <span class="span2"><%= ingredient.name %></span>
    <span class="span2"><%= ingredient.quantity %></span>
    <span class="span3"><%= @user.pantry_items.find_by(:ingredient_id => ingredient.id).created_at %></span>
</li>
但是在呈现时给出了一个错误:PG::error:error:column“components.id”必须出现在GROUP BY子句中,或者必须在聚合函数中使用

2。是否可以添加并返回分组结果的列?例如,我有:

Name            Quantity

Oak 2x2             2

Oak 2x2             4
返回橡树2x26


我猜它看起来像是
@user.components.select('components,sum(quantity))
,但我不确定如何将其包含在分组中,并在视图中正确输出。

您可以在ActiveRecord关联中使用SQL接口:

has_many :ingredients, -> { group("name").select("ingredients.*", "SUM(ingredients.quantity) AS quantity") }, through: :project_items

这可能需要更多的调整才能正确,并在

中进行了更多的解释。有没有办法将其放入命名的作用域中,或者将其置于控制器中?以允许其动态?是的,我并不总是希望user.components按总和进行分组。您可以将其放入这样的作用域:
scope:summared,->(var){SQL}
我将在接下来的几天内对此进行一次尝试,暂时不讨论这个问题。
: SELECT "ingredients".* FROM "ingredients" INNER JOIN "project_items" ON "ingredients"."id" = "project_items"."ingredient_id" WHERE "project_items"."user_id" = $1 GROUP BY name
Name            Quantity

Oak 2x2             2

Oak 2x2             4
has_many :ingredients, -> { group("name").select("ingredients.*", "SUM(ingredients.quantity) AS quantity") }, through: :project_items