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 ...
随机推荐
- KingbaseESV8R6识别IO使用率过高
前言 数据库正常运行离不开I/O的使用,在操作系统上,I/O又离不开存储的性能及使用方式,我们可以在存储层利用raid条带化技术使IOPS达到最佳性能. 本篇文章有助于确认数据库I/O使用率过高的原因 ...
- KingbaseES 原生XML系列三--XML数据查询函数
KingbaseES 原生XML系列三--XML数据查询函数(EXTRACT,EXTRACTVALUE,EXISTSNODE,XPATH,XPATH_EXISTS,XMLEXISTS) XML的简单使 ...
- Python爬虫爬取国家统计局网站【统计用区划和城乡划分代码】并存入MySQL数据库
国家统计局网站相关分级页面截图 基本思路 爬取每个页面的a标签内容,生成省市两级数据字典,最后合成区县对应的链接,爬取第三层区划代码和名字,结合省市两级名字生成最后的标准. 代码 1 import p ...
- C++一些例子
虚析构 #include<iostream> class Base { public: Base() { std::cout << "base 构造" &l ...
- MySQL检索和过滤数据
注意 多条SQL语句必须以分号(:)分隔: SQL语句不区分大小写: 在处理SQL语句时,其中所有空格都被忽略: 当选择多个列是,一定要在列名之间加上逗号,但最后一个列名后不加. SELECT语句 检 ...
- 数据库锁起来了,把事务清掉sql
select concat('kill ',id,';') from information_schema.`PROCESSLIST` where state !='executing' 将上述代码执 ...
- #K-D Tree#洛谷 2093 [国家集训队]JZPFAR
题目 平面上有 \(n\) 个点.现在有 \(m\) 次询问,每次给定一个点 \((px, py)\) 和一个整数 \(k\), 输出 \(n\) 个点中离 \((px, py)\) 的距离第 \(k ...
- #博弈论#Poj 2484 A Funny Game
题目 \(n\)个石子排成一圈,每次可以取一个或相邻的一对, 取完为胜,问先手是否必胜 分析 无论先手如何取,后手都能模仿先手的取法. 比如说,当石子个数为奇数时先手取相邻的一对,后手可以将对面的那一 ...
- 格式化字符串走过的坑 pwn109
格式化字符串走过的坑 pwn109 今天做的一道题有一个坑我调试半天终于打通了,格式化字符串的坑,确实不少,东西也比较多容易忘记,怎么说呢,功夫在平时,经验少了 老规矩先看一下保护 Full RELR ...
- 基于Canvas实现的简历编辑器
基于Canvas实现的简历编辑器 大概一个月前,我发现社区老是给我推荐Canvas相关的内容,比如很多 小游戏.流程图编辑器.图片编辑器 等等各种各样的项目,不知道是不是因为我某一天点击了相关内容触发 ...