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

查询近三个月的数量

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

查询上个月的数量

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

查询本月的数量

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

近一周

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

修改超过一个小时的数据

    # 修改超过一个小时的任务
    # 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)
      .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

in 查询

client = Client.find([1, 10])
# SELECT * FROM clients WHERE (clients.id IN (1,10))
# 如果所提供的主键都没有匹配记录,那么 find 方法会抛出 ActiveRecord::RecordNotFound 异常。

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')

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
[Haima的博客] http://www.cnblogs.com/haima/
原文地址:https://www.cnblogs.com/haima/p/15106419.html