SET*_*SET 6 ruby ruby-on-rails rails-activerecord
我有一个包含分页数据的表,这是我为每个页面选择数据的方式:
@visitors = EventsVisitor
.select('visitors.*, events_visitors.checked_in, events_visitors.checkin_date, events_visitors.source, events_visitors.id AS ticket_id')
.joins(:visitor)
.order(order)
.where(:event_id => params[:event_id])
.where(filter_search)
.where(mode)
.limit(limit)
.offset(offset)
Run Code Online (Sandbox Code Playgroud)
另外,要构建表分页,我需要知道记录的总数.目前我的解决方案非常粗糙:
total = EventsVisitor
.select('count(*) as count, events_visitors.*')
.joins(:visitor)
.order(order)
.where(:event_id => params[:event_id])
.where(filter_search)
.where(mode)
.first()
.count
Run Code Online (Sandbox Code Playgroud)
所以我的问题如下 - 为当前页面和记录总数选择有限数据的最佳ruby方式是什么?
我注意到如果我做@ visitor.count - 将生成额外的SQL查询:
SELECT COUNT(count_column) FROM (SELECT 1 AS count_column FROM `events_visitors` INNER JOIN `visitors` ON `visitors`.`id` = `events_visitors`.`visitor_id` WHERE `events_visitors`.`event_id` = 1 LIMIT 15 OFFSET 0) subquery_for_count
Run Code Online (Sandbox Code Playgroud)
首先,我不明白发送额外查询以获取我们已经拥有的数据的原因是什么,我的意思是在我们从@visitors的数据库获取数据后,我们可以使用ruby计算它而无需发送额外的查询到DB.
第二 - 我认为也许有一些方法可以使用像.total_count这样的东西,它会产生类似的'count(*)'查询但没有那么无用的'限制/偏移'?
你应该限制和抵消 http://guides.rubyonrails.org/active_record_querying.html#except.看看kaminari如何做到这一点 https://github.com/kaminari/kaminari/blob/92052eedf047d65df71cc0021a9df9df1e2fc36e/lib/kaminari/models/active_record_relation_methods.rb#L11
所以它可能是这样的
total = @visitors.except(:offset, :limit, :order).count
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2570 次 |
| 最近记录: |