我正在尝试向我的应用程序添加一个高级搜索选项,用户可以在其中根据来自 3 个不同模型的属性搜索某些链接。
我的应用程序设置User has_many :websites
为Website has_many :links
Link has_many :stats
我知道如何在 Rails 中使用连接或包含等创建 SQL 查询,但我遇到了困难,因为我只想检索每个链接而不是所有链接的最新统计信息 - 我不知道最有效的方法来做到这一点.
例如,假设一个用户有 2 个网站,每个网站有 10 个链接,每个链接有 100 个统计信息,总共 2,022 个对象,但我只想搜索 42 个对象(每个链接只有 1 个统计信息)。
一旦我在数据库查询中只获得了这 42 个对象,我就可以添加.where("attribute like ?", user_input)
并返回正确的链接。
更新
我尝试将以下内容添加到我的 Link 模型中:
has_many :stats, dependent: :destroy
has_many :one_stat, class_name: "Stat", order: "id ASC", limit: 1
但这似乎不起作用,例如,如果我这样做:
@links = Link.includes(:one_stat).all
@links.each do |l|
puts l.one_stat.size
end
我没有得到1, 1, 1...
所有统计数据的数量:125, 40, 76...
。
我可以使用限制选项来获得我想要的结果还是不能这样工作?
第二次更新
我已经根据 Erez 的建议更新了我的代码,但仍然无法正常工作:
has_one :latest_stat, class_name: "Stat", order: "id ASC"
@links = Link.includes(:latest_stat)
@links.each do |l|
puts l.latest_stat.indexed
end
=> true
=> true
=> true
=> false
=> true
=> true
=> true
Link.includes(:latest_stat).where("stats.indexed = ?", false).count
=> 6
Link.includes(:latest_stat).where("stats.indexed = ?", true).count
=> 7
它应该返回 1 和 6,但它仍在检查所有统计信息,而不仅仅是最新的。