Sql 是否有更有效的方法获取此数组?

Sql 是否有更有效的方法获取此数组?,sql,ruby-on-rails,ruby,performance,sqlite,Sql,Ruby On Rails,Ruby,Performance,Sqlite,我有一个模型项,用户可以通过创建新的UpVote或DownVote对其进行投票。创建UpVote或Downvote时,它会记录用户的ip地址和项目的id。我想列出前100个项目的数组,这些项目没有被当前用户的ip投票 到目前为止,我的情况如下: 模式 create_table "up_votes", force: true do |t| t.string "ip" end create_table "down_votes", force: true do |t| t.string

我有一个模型项,用户可以通过创建新的UpVote或DownVote对其进行投票。创建UpVote或Downvote时,它会记录用户的ip地址和项目的id。我想列出前100个项目的数组,这些项目没有被当前用户的ip投票

到目前为止,我的情况如下:

模式

create_table "up_votes", force: true do |t|
  t.string   "ip"
end

create_table "down_votes", force: true do |t|
  t.string   "ip"
end
型号

class Item < ActiveRecord::Base

  def up_votes_array
    self.up_votes.map(&:ip).to_a
  end

  def down_votes_array
    self.down_votes.map(&:ip).to_a
  end

  def up_voted?(ip)
    self.up_votes_array.include? ip
  end

  def down_voted?(ip)
    self.down_votes_array.include? ip
  end

这是可行的,但有些东西似乎不必要地复杂,我担心随着数据库的增长,它可能会变得效率低下。是否有更有效的方法获取此阵列


我使用的是Rails 4和Sqlite3。

我认为理想的查询如下:

Item.where(show:true).加入(:向上投票).加入(:向下投票).其中('up\u voces.ip!=?',request.remote\u ip).其中('down\u voces.ip!=?',request.remote\u ip).限制(100)

这将生成一个最佳查询,并在内存中加载100行,而在给定的查询中,它会为
加载整个表,并在所有的上行投票和下行投票上进行迭代以进行检查

您也可以将查询合并为:
Item.where(show:true)。连接(:up\u vots)。连接(:down\u vots)。其中('up\u vots.ip!=?and down\u vots.ip!=',request.remote\u ip,request.remote\u ip)。限制(100)

这里的
是什么。它和物品有什么联系?对不起,我把它和我的另一张桌子弄混了。应该是
。这样行吗?如果某个项目同时拥有会话ip和其他ip的up_投票,该怎么办?它至少有一张赞成票,是!=ip,所以它将在不应该被选择的时候被选择。如果它的任何一个向上投票或向下投票有request.remote\u ip,它将不会选择该项目,即使该项目的其他向上投票或向下投票有一些ip。它应该返回如下查询:
select*from items internal join up\u voces on items.id=up\u voces.item\u id internal join down\u voces on items.id where up\u voces.ip“127.0.0.1”和down\u voces.ip“127.0.0.1”limit 3
。试试看,酷。总是受教育,在这里闲逛。:)
@not_voted = Item.where(show: true).select { |item| !item.up_voted?(request.remote_ip) }.select { |thing| !item.down_voted?(request.remote_ip) }.sort_by(&:alphabetical).reverse.first(100).shuffle