Ruby on Rails Active Record数据库常用操作
文档地址:
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数据库常用操作的更多相关文章
- php模拟数据库常用操作效果
test.php <?php header("Content-type:text/html;charset='utf8'"); error_reporting(E_ALL); ...
- DBA必备:MySQL数据库常用操作和技巧
DBA必备:MySQL数据库常用操作和技巧 2011-02-25 15:31 kaduo it168 字号:T | T MySQL数据库可以说是DBA们最常见和常用的数据库之一,为了方便大家使用,老M ...
- Active Record 数据库模式-增删改查操作
选择数据 下面的函数帮助你构建 SQL SELECT语句. 备注:如果你正在使用 PHP5,你可以在复杂情况下使用链式语法.本页面底部有具体描述. $this->db->get(); 运行 ...
- 11月28日 记录一个错误❌,看ruby on rails --active support core extensions--present? && presence && duplicable?
❌错误 1. @job.resume.count: 提示❌ undefined method `resume' ✅: @job.resumes.count //解释:调出某一个job的所有简历, ...
- Yii2框架 数据库常用操作
通用: use yii\db\Query; $query = new Query(); 查询: Query: $rows = (new \yii\db\Query()) ->select(['c ...
- MySQL数据库常用操作和技巧
MySQL数据库可以说是DBA们最常见和常用的数据库之一,MySQL的广泛应用,也使更多的人加入到学习它的行列之中.下面是老MySQL DBA总结的MySQL数据库最常见和最常使用的一些经验和技巧,分 ...
- Mysql数据库常用操作语句大全
零.用户管理: 1.新建用户: >CREATE USER name IDENTIFIED BY 'ssapdrow'; 2.更改密码: >SET PASSWORD FOR name=PAS ...
- JDBC数据库常用操作(mysql)
JDBC英文名称:JavaDataBaseConnectivity中文名称:java数据库连接简称:JDBCJDBC是一种用于执行SQL语句的JavaAPI,可以为多种关系数据库提供统一访问,它由一组 ...
- Mysql数据库常用操作整理
0.说明 MySQL数据库是一个十分轻便的数据库管理系统,相比大型的数据库管理系统如Oracle,MySQL更拥有轻便.灵活.开发速度快的特色,更适用于中小型数据的存储与架构,被数以万计的网站采用.从 ...
- MySQL数据库 常用操作
1:使用SHOW语句找出在服务器上当前存在什么数据库: mysql> SHOW DATABASES; 2:创建一个数据库MYSQLDATA mysql> CREATE DATABASE M ...
随机推荐
- KingbaseES V8R6 等待事件之CLogControlLock
前言 Kingbase数据库的tuple行头部来标识这条记录的事务结束状态(未知.已提交.已回滚),在事务提交时如果并发更新100万行记录,需要对多个page的tuple进行更改,这种繁重的操作会对数 ...
- sql分页遍历出现重复数据原因与解决方案
1. 问题描述 有同时反馈,直接通过如下的sql进行分页查询,分页会出现重复数据,于是乎我专门查了相关了资料,整理了一下. -- 根据sort字段对dbname进行排序,每五百条数据一页 SELECT ...
- Android开发 活动activity
一.关于Activity 关于Activity必须要了解的内容有:Activity的生命周期.android任务栈.Activity启动模式.scheme跳转协议. 1.1 什么是Activity ...
- #Pollard-Rho,高精度#洛谷 3499 [POI2010]NAJ-Divine Divisor
题目 给定\(m\)个数\(a_i\),令\(n=\prod_{i=1}^m a_i\), 问有多少个大于1的正整数\(d\)满足\(d^{\max k}|n\) 并输出\(\max k\),\(m\ ...
- 许北林:我为什么加入OpenHarmony生态?又为什么要做“启航KP”开发套件?
许北林 软通动力 资深项目经理 在全球开源趋势下,中国正逐渐成为全球开源软件的主要使用者和核心贡献者.今天我们来认识一位接触 OpenHarmony 不到一年,便带领团队成功开发出一款"启航 ...
- VS2019快捷键
快捷键功能CTRL + SHIFT + B生成解决方案CTRL + F7 生成编译CTRL + O 打开文件CTRL + SHIFT + O打开项目CTRL + SHIFT + C显示类视图窗口F4 ...
- BI工具的应用能给企业带来哪些帮助?
大数据时代的到来,加快了企业的信息化进程,越来越多的企业选择应用BI工具于企业的日常经营运作之中.BI即商业智能,我们可以将其理解其为改善业务经营决策的一套解决方案.经过多年的发展,BI已经从最初的& ...
- 如何在openGauss 2.1.0中使用Job
如何在 openGauss 2.1.0 中使用 Job 如何在 openGauss 2.1.0 中使用 Job Job 类似 unix 中的 crontab,有定时执行的功能,可以在指定的时间点或每天 ...
- 打造美团外卖新体验,HarmonyOS SDK 持续赋能开发者共赢鸿蒙生态
从今年 8 月起,所有升级到 HarmonyOS 4 的手机用户在美团外卖下单后,可通过屏幕上的一个"小窗口",随时追踪到"出餐.取餐.送达"等订单状态.这个能 ...
- CentOS 6.5快速部署HTTP WEB服务器和FTP服务器
CentOS 6.5快速部署HTTP WEB服务器和FTP服务器 时间:2014-03-29 来源:服务器之家 投稿:root 点击:210次 [题记]本文使用CentOS 6.5m ...