gpt4 book ai didi

ruby-on-rails - 如何组合来自多个 has_many :through queries? 的 ActiveRecord 结果

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:38 25 4
gpt4 key购买 nike

基本上,我有一个带有标签系统的应用程序,当有人搜索标签“badger”时,我希望它返回标记为“badger”、“Badger”和“Badgers”的记录。使用单个标签,我可以这样做来获取记录:

@notes = Tag.find_by_name(params[:tag_name]).notes.order("created_at DESC")

而且效果很好。但是,如果我得到多个标签(这只是大写和小写 - 我还没有弄清楚's'位):

Tag.find(:all, :conditions => [ "lower(name) = ?", 'badger'])

我不能使用 .notes.order("created_at DESC") 因为有多个结果。所以,问题是…… 1) 我这样做的方式正确吗? 2) 如果是这样,我如何按顺序恢复所有记录?

非常感谢任何帮助!

最佳答案

一种实现方式是:

@notes = []
Tag.find(:all, :conditions => [ "lower(name) = ?", 'badger']).each do |tag|
@notes << tag.notes
end
@notes.sort_by {|note| note.created_at}

但是您应该知道,这就是所谓的 N + 1 查询,因为它在外部部分进行一次查询,然后针对每个结果进行一次查询。这可以通过将第一个查询更改为来优化:

Tag.find(:all, :conditions => [ "lower(name) = ?", 'badger'], :includes => :notes).each do |tag|

如果你使用的是Rails 3或以上版本,可以稍微重写一下:

Tag.where("lower(name) = ?", "badger").includes(:notes) do |tag|

关于ruby-on-rails - 如何组合来自多个 has_many :through queries? 的 ActiveRecord 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11568448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com