文档地址:

https://freed.gitee.io/rails-guides/active_record_querying.html

创建

## 记录日志
Log.create(logtype: 2, email: current_user.email, user_id: current_user.cas_uid,
url: '/api/exploit/rule_list',
info: "product: #{products} records: #{ret_rule.nil? ? 0 : ret_rule.size}",
ip: env["HTTP_X_REAL_IP"] || env["REMOTE_ADDR"])

批量插入

# 批量插入数据库
black_ips = ['127.0.0.1','127.0.0.2']
begin
# 批量插入
time = Time.now
BlackIp.bulk_insert(:ip, :created_at, :updated_at) do |black_ip|
black_ip.set_size = 1000
black_ips.each do |ip|
black_ip.add [ip, time, time]
end
end
rescue Exception => e
puts "#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} #{self.jid} save blackip Error: #{e.message}"
end

判断是否存在

IpList.exists?(ip: "#{env["HTTP_X_REAL_IP"] || env["REMOTE_ADDR"]}")

Ruby on Rails 日期查询方法

查询近超过1个小时的数量

Order.where(' created_at <= ? ', DateTime.now - 1.hours).count

生成sql:

SELECT COUNT(*) FROM order WHERE ( created_at <= '2022-05-20 17:28:10.111545' )

查询近三个月的数量

Order.where(' created_at >= ? ', DateTime.now - 3.month).count

生成sql:

SELECT COUNT(*) FROM order WHERE ( created_at >= '2022-02-20 18:26:57.407358' )

查询上个月的数量

Order.where(created_at: (DateTime.now - 1.month).beginning_of_month..DateTime.now.beginning_of_month).count

生成sql:

SELECT COUNT(*) FROM order WHERE (order.created_at BETWEEN '2022-04-01 00:00:00' AND '2022-05-01 00:00:00')

查询本月的数量

Order.where(' created_at >= ? ', DateTime.now.beginning_of_month).count

生成sql:

SELECT COUNT(*) FROM order WHERE (order.created_at BETWEEN '2022-04-01 00:00:00' AND '2022-05-01 00:00:00')

近一周

Order.where(' created_at >= ? ', DateTime.now - 7.day).count

生成sql:

SELECT COUNT(*) FROM tasks WHERE ( created_at >= '2022-05-13 18:21:58.804635' )

修改超过一个小时的数据

    # 修改超过一个小时的任务
# past_time = (n_time - 1.hours).strftime("%Y-%m-%d %H:%M:%S")
# => "2021-08-05 20:55:31"
CategoryStatistic
.where("state = 'init' and end_at IS NULL ")
.where("begin_at<=?", DateTime.now - 1.hours)
.where("start_computing_time IS NULL")
.update_all(state: FAILED, end_at: n_time, updated_at: n_time)

运行结果:

 UPDATE `category_statistics` SET `category_statistics`.`state` = 'failed', `category_statistics`.`end_at` = '2021-08-05 22:27:45', `category_statistics`.`updated_at` = '2021-08-05 22:27:45' WHERE (state = 'init' and end_at IS NULL ) AND (begin_at<='2021-08-05 21:27:45.684015')

first / last 查询一条


ret = client = Client.find(10)
ret = Client.where("product = ? and published = 1", products).select("producturl").first
ret = Client.where("product = ? and published = 1", products).select("producturl").last #查列,匹配第一条
res = BlackIp.where(ip:"106.83.249.151").pluck(:is_china).first
(0.7ms) SELECT `black_ips`.`is_china` FROM `black_ips` WHERE `black_ips`.`ip` = '106.83.249.151'

in 查询

client = Client.find([1, 10])
# SELECT * FROM clients WHERE (clients.id IN (1,10))
# 如果所提供的主键都没有匹配记录,那么 find 方法会抛出 ActiveRecord::RecordNotFound 异常。 IpInfo.select(:ip).where(ip: ["114.223.55.93","114.223.55.95"])
IpInfo Load (1.1ms) SELECT `ip_infos`.`ip` FROM `ip_infos` WHERE `ip_infos`.`ip` IN ('114.223.55.93', '114.223.55.95') distinct_rules = client.select(:id, :name, :age, :level :product).where(published: true).where("product in (:key) or en_product in (:key) ", key: products) if distinct_rules.present?
distinct_rule_jsons = distinct_rules.map { |rule| { "id" => rule.id, "product" => rule.product, "name" => rule.name, "age" => rule.age } }
data = distinct_rule_jsons.map { |obj| obj["product"] }
else
data
end
puts "data #{data}"

not in 查询

BlackIp.where("ip not in (:key) ", key: ["114.223.55.93","114.223.55.95"]).pluck(:ip)
(32.7ms) SELECT `black_ips`.`ip` FROM `black_ips` WHERE (ip not in ('114.223.55.93','114.223.55.95') ) BlackIp.where.not(ip: ["114.223.55.94","114.223.55.92"]).pluck(:ip)
(47.0ms) SELECT `black_ips`.`ip` FROM `black_ips` WHERE (`black_ips`.`ip` NOT IN ('114.223.55.94', '114.223.55.92'))

or 查询

q_product = 'xxx有限公司' + "%"
ret = Client.where("(product like ? or company like ?) and published = 1", q_product, q_product).limit(5)

or like

@client_title, @other_titles = [], []
clients = Client.where(published: true).where("product like :key or product like :key2 or company like :key or company like :key2", key: "#{q}%", key2: "%#{q}")
client = []
clients.first(3).each do |r|
client << %Q[app="#{r.product}"]
@client_title << r.product
end clients.offset(3).each do |r|
@other_titles << r.product
end @keyword = params[:keyword].to_s.strip
@rs = current_user.rules.where("company like :key or product like :key or rule like :key or producturl like :key", key: "%#{@keyword}%").paginate(:page => params[:page],
:per_page => 20).order('id DESC') ret_rule = Rule.where("(product like ? or company like ?) and published = 1", q_product, q_product).limit(limit.to_i)
total = ret_rule.nil? ? 0 : ret_rule.size
if ret_rule.nil?
{error: true, errmsg: "not found product list"}
else
xproduct_list = []
ret_rule.each { |r|
product_list << r["product"]
} {error: false, data: product_list}
end

in or in

distinct_rules = client.select(:id, :name, :age, :level :product).where(published: true).where("product in (:key) or en_product in (:key) ", key: products)

if distinct_rules.present?
distinct_rule_jsons = distinct_rules.map { |rule| { "id" => rule.id, "product" => rule.product, "name" => rule.name, "age" => rule.age } }
data = distinct_rule_jsons.map { |obj| obj["product"] }
else
data
end
puts "data #{data}"

sum 相加

list = Client.where("change_coin > 0").order(id: :desc)
in_total_coin = Client.where(category: "in").sum(:change_coin)+Order.where(state: 1, subject: 'F币').sum(:amount)
out_total_coin = Client.where(category: "out").sum(:change_coin)

批量修改

Client.update_all(state: "init")
Client.where(id: init_ip_infos.pluck(:id)).update_all(state: "init")
Client.where(id: @attrs.map{|obj| obj[:rule_record_id]}).update_all(state: "success")
Client.where("isvip=1 and vip_level=0").update_all(vip_level: 1)

批量删除

  def self.update_rules
path = "/Users/zcy/Downloads/rule.txt"
new_products = open(path).readlines.map{|ip| ip.strip}
group_rules = Rule.all.in_groups_of(5000).map{|obj| obj.compact}
group_rules.each do |rules|
rule_products = rules.map{|rule| rule.product}
delete_products = rule_products - new_products
Rule.where(product: delete_products).delete_all
end
end puts "restart_task66666677------------>"
region = ["湖北", "山西", "福建","海南"]
sheet_category = 'wangluo'
Record.where(region: region, sheet_category: sheet_category).delete_all

join

Rule.joins(:categories).select("categories.title, rules.id, rules.product, rules.rule").where(rules: {published: true})
total = et_rule.nil? ? 0 : ret_rule.size
titles = ret_rule.group_by(&:title)

exists

IpWhitelist.exists

Ruby on Rails Active Record数据库常用操作的更多相关文章

  1. php模拟数据库常用操作效果

    test.php <?php header("Content-type:text/html;charset='utf8'"); error_reporting(E_ALL); ...

  2. DBA必备:MySQL数据库常用操作和技巧

    DBA必备:MySQL数据库常用操作和技巧 2011-02-25 15:31 kaduo it168 字号:T | T MySQL数据库可以说是DBA们最常见和常用的数据库之一,为了方便大家使用,老M ...

  3. Active Record 数据库模式-增删改查操作

    选择数据 下面的函数帮助你构建 SQL SELECT语句. 备注:如果你正在使用 PHP5,你可以在复杂情况下使用链式语法.本页面底部有具体描述. $this->db->get(); 运行 ...

  4. 11月28日 记录一个错误❌,看ruby on rails --active support core extensions--present? && presence && duplicable?

    ❌错误 1. @job.resume.count: 提示❌   undefined method `resume' ✅: @job.resumes.count  //解释:调出某一个job的所有简历, ...

  5. Yii2框架 数据库常用操作

    通用: use yii\db\Query; $query = new Query(); 查询: Query: $rows = (new \yii\db\Query()) ->select(['c ...

  6. MySQL数据库常用操作和技巧

    MySQL数据库可以说是DBA们最常见和常用的数据库之一,MySQL的广泛应用,也使更多的人加入到学习它的行列之中.下面是老MySQL DBA总结的MySQL数据库最常见和最常使用的一些经验和技巧,分 ...

  7. Mysql数据库常用操作语句大全

    零.用户管理: 1.新建用户: >CREATE USER name IDENTIFIED BY 'ssapdrow'; 2.更改密码: >SET PASSWORD FOR name=PAS ...

  8. JDBC数据库常用操作(mysql)

    JDBC英文名称:JavaDataBaseConnectivity中文名称:java数据库连接简称:JDBCJDBC是一种用于执行SQL语句的JavaAPI,可以为多种关系数据库提供统一访问,它由一组 ...

  9. Mysql数据库常用操作整理

    0.说明 MySQL数据库是一个十分轻便的数据库管理系统,相比大型的数据库管理系统如Oracle,MySQL更拥有轻便.灵活.开发速度快的特色,更适用于中小型数据的存储与架构,被数以万计的网站采用.从 ...

  10. MySQL数据库 常用操作

    1:使用SHOW语句找出在服务器上当前存在什么数据库: mysql> SHOW DATABASES; 2:创建一个数据库MYSQLDATA mysql> CREATE DATABASE M ...

随机推荐

  1. 汇编语言-使用BIOS进行键盘输入和磁盘读写

    int9中断例程对键盘输入的处理   键盘输入将引发9号中断,BIOS提供了int9中断例程.CPU在9号中断发生后,执行int 9中断例程,从60h端口读出扫描码,并将其转化为相应的ASCII码或状 ...

  2. #最大公约数,容斥#洛谷 3166 [CQOI2014]数三角形

    题目 分析 总方案就是\(C(n*m,3)\),考虑减掉不合法的方案, 横向\(n*C(m,3)\),纵向\(m*C(n,3)\)再减去斜着的, 对于\((x_1,y_1)(x_2,y_2),x_1& ...

  3. JDK 14的新特性:文本块Text Blocks

    目录 举个例子 Indentation编排 Escaping转义 formatted格式化 总结 说起来,Text Blocks是在JDK13中以第一次预览版本引入的.现在在JDK14中是第二次预览版 ...

  4. 玩转HarmonyOS专项测试,轻松上架“五星”高品质应用

      作者:David,华为测试服务专家 随着信息技术的高速发展,移动应用与人们生活日益紧密,面向各类场景的应用层出不穷,什么样的应用更受用户青睐呢?在满足用户功能需求之上,一个好的应用要能运行稳定.流 ...

  5. Next.js 实战

    0x1 CSR,SSR,SSG CSR 客户端渲染(Client-Side Rendering).常见 B 端 Web 应用开发模式,前后端分离,服务器压力相对更轻,渲染工作在客户端进行,服务器直接返 ...

  6. oracle 数据库连接

    前言 关于oracle 数据库如何连接,我一开始以为和mysql 和 sql server一样,写好连接语句然后调用相应的dll. 知道我遇到了两个错误: 1.64位程序不能去驱动32位客户端 2.O ...

  7. This beta version of Typora is expired, please download and install a newer version. 实测最简单有效的方案

    This beta version of Typora is expired, please download and install a newer version. 实测最简单有效的方案 一.问题 ...

  8. .NET开源免费的跨平台框架 - MAUI(附学习资料)

    前言 前几天分享了一个.NET MAUI开源免费的UI工具包 - Uranium,然后技术群有不少同学问.NET MAUI是不是免费的?能做什么?今天特意写这篇文章来介绍一下.NET开源.免费(基于M ...

  9. 力扣209(java&python)-长度最小的子数组(中等)

    题目: 给定一个含有 n 个正整数的数组和一个正整数 target . 找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, ...

  10. anconda配置tensorflow环境

    一.anconda的安装 1.进入Anaconda官网并按照电脑配置选择合适的安装包 Anaconda官网:https://www.anaconda.com/ 点击进入 不同的三个版本,分别是wind ...