rails上的SQL查询

rails上的SQL查询,sql,ruby-on-rails,ruby,Sql,Ruby On Rails,Ruby,我正在尝试查找列表中已完成的所有项目。我尝试在Todoitem模型中执行查询,但它显示[] 我做错了什么 我的疑问是: Todoitem.find_by_sqlSELECT count*AS count_全部从todoitems ti内部连接到列表tl,其中ti.completed='true'和ti.todolist_id=tl.id 我的模型是这样的: class Todolist < ApplicationRecord belongs_to :user, required: fa

我正在尝试查找列表中已完成的所有项目。我尝试在Todoitem模型中执行查询,但它显示[] 我做错了什么

我的疑问是:

Todoitem.find_by_sqlSELECT count*AS count_全部从todoitems ti内部连接到列表tl,其中ti.completed='true'和ti.todolist_id=tl.id

我的模型是这样的:

class Todolist < ApplicationRecord
  belongs_to :user, required: false
  has_many :todoitems, dependent: :destroy
end

class Todoitem < ApplicationRecord
  belongs_to :todolist
end
Todoitem.find_by_sql("SELECT count(*) AS count_all FROM todo....").first.count_all
Todolist.joins(:todoitems).where(todoitems:{completed:'true' }).count

要查找todolist中已完成的所有项,您的查询将起作用。我假设您将completed的布尔值存储为字符串,因为您在原始查询中使用了字符串

但是,由于您仅选择count*作为count\u all,因此必须从数组中的第一个元素中查看count\u all,如下所示:

class Todolist < ApplicationRecord
  belongs_to :user, required: false
  has_many :todoitems, dependent: :destroy
end

class Todoitem < ApplicationRecord
  belongs_to :todolist
end
Todoitem.find_by_sql("SELECT count(*) AS count_all FROM todo....").first.count_all
Todolist.joins(:todoitems).where(todoitems:{completed:'true' }).count
这将返回所有ToDoList中已完成的todoitems总数

更活跃的记录方式如下:

class Todolist < ApplicationRecord
  belongs_to :user, required: false
  has_many :todoitems, dependent: :destroy
end

class Todoitem < ApplicationRecord
  belongs_to :todolist
end
Todoitem.find_by_sql("SELECT count(*) AS count_all FROM todo....").first.count_all
Todolist.joins(:todoitems).where(todoitems:{completed:'true' }).count
要获取至少有一个已完成待办事项的列表数,可以使用:

Todolist.joins(:todoitems).group(:id).where(todoitems:{completed:'true' }).length
Todolist.joins(:todoitems).group(:id).where(todoitems:{completed:'true' }).count
Todolist.joins(:todoitems).where(id: id, todoitems:{completed:'true' }).count
要查找每个列表中可以使用的已完成项目数,请执行以下操作:

Todolist.joins(:todoitems).group(:id).where(todoitems:{completed:'true' }).length
Todolist.joins(:todoitems).group(:id).where(todoitems:{completed:'true' }).count
Todolist.joins(:todoitems).where(id: id, todoitems:{completed:'true' }).count
这将返回一个以列表id为键、以已完成项目数为值的散列

要获取特定任务中已完成项目的数量,可以使用:

Todolist.joins(:todoitems).group(:id).where(todoitems:{completed:'true' }).length
Todolist.joins(:todoitems).group(:id).where(todoitems:{completed:'true' }).count
Todolist.joins(:todoitems).where(id: id, todoitems:{completed:'true' }).count

你可以沿着这条路走

Rails5-Postgresql

在此查询中,它将仅显示具有todoitems的todolist

另外,这将仅显示没有结果为0的todoitems的todolist


我希望这对您有所帮助。

您如何使用查询结果?它显示在页面:Completed Todos:[]是已完成的todo数。我们需要将该类呈现为Todoitem