首页 > 解决方案 > Ruby ActiveRecord 批量检索新插入的记录?

问题描述

这与我之前的查询有关。

我可以使用以下查询从 ActiveRecord 获取批量记录:

Client.offset(15 * iteration).first(15)

我遇到了用户输入新记录的问题。

假设有 100 条记录,批次为 15。前 6 次迭代(90 条记录)和最后一次迭代(10 条记录)有效。但是,如果有新条目进入(总共有 101 条记录),程序将失败,因为它会:

a) 如果迭代计数器设置为递增,它将查询超出 101 范围的记录,导致不返回任何内容。

b) 如果迭代计数器被修改为仅当整批 15 个项目完成时才递增,则重复最后 14 个项目加上 1 个新项目。

如何获取新发布的记录?

飞镖代码:

_getData() async {
    if (!isPerformingRequest) {
      setState(() {
        isPerformingRequest = true;
      });

      //_var represents the iteration counter - 0, 1, 2 ...
      //fh is a helper method returning records in List<String>
      List<String> newEntries = await fh.feed(_var);

      //Count number of returned records.
      newEntries.forEach((i) => _count++);

      if (newEntries.isEmpty) {
        ..
        }
      } else {

        //if number of records is 10, increment _var to go to the next batch of 10.
        if(_count == 10) {
          _var++;
          _count = 0;
        }
        //but if count is not 10, stay with the same batch (but previously counted/display records will be shown again)
      }

      setState(() {
        items.addAll(newEntries);
        isPerformingRequest = false;
      });
    }
  }

标签: rubyactiverecorddart

解决方案


推荐阅读