【发布时间】:2015-04-26 20:52:17
【问题描述】:
我有一个模型项目,用户可以通过创建新的 UpVote 或 DownVote 对其进行投票。创建 UpVote 或 Downvote 时,它会记录用户的 ip 地址和 Item 的 id。我想列出当前用户的ip没有投票的前100个Item的数组。
到目前为止,这是我所拥有的:
架构
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
控制器
@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
它可以工作,但有些东西似乎不必要地复杂,我担心随着数据库的增长,它可能会变得低效。有没有更有效的方法来获取这个数组?
我正在使用 Rails 4 和 Sqlite3。
【问题讨论】:
-
这里的
Thing是什么。它和Item有什么关系? -
糟糕,对不起,我把它和我的另一张桌子混在一起了。应该是
Item。
标签: sql ruby-on-rails ruby performance sqlite