使用SQL函数的插入/更新中的ActiveRecord [英] Use SQL functions for insert/update in ActiveRecord

查看:207
本文介绍了使用SQL函数的插入/更新中的ActiveRecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要存储的IP地址(IPv4和IPv6)在我的Rails应用程序。我已经安装了延伸到MySQL 增加功能的IP字符串转换为二进制这将使我通过IP查询范围内轻松。

我可以使用转义SQL语句的SELECT类型的查询,那是容易的。

最艰难的部分是,我还需要一种方法来覆盖字段被转义,插入/更新语句的方式。

这ActiveRecord的声明

 新_IP = Ip.new
new_ip.start =1.2.3.4
new_ip.save
 

生成下列SQL语句

  INSERT INTO IPS(开始)VALUES(inet6_pton(1.2.3.4));
 

有没有办法做到这一点?我试了很多东西,包括首要的ActiveRecord :: Base的#arel_attributes_values​​ ,没有运气:生成的SQL被转换成二进制文件(如果该事项,我的专栏是一个MySQL VARBINARY( 16))。

解决方案

 的ActiveRecord :: Base.connection.execute(INSERT INTO IPS(开始)VALUES(inet6_pton(1.2.3.4 ')))
 

I want to store IP addresses (v4 and v6) in my rails application. I have installed an extension to MySQL adds functions to convert ip strings to binary which will allow me to query by IP range easily.

I can use unescaped sql statements for SELECT type queries, thats easy.

The hard part is that I also need a way to overwrite the way the field is escaped for insert/update statements.

This ActiveRecord statement

new_ip = Ip.new
new_ip.start = '1.2.3.4'
new_ip.save

Should generate the following SQL statement

INSERT INTO ips(start) VALUES(inet6_pton('1.2.3.4'));

Is there a way to do this? I tried many things, including overriding ActiveRecord::Base#arel_attributes_values, without luck : the generated sql is always converted to binary (if that matters, my column is a MySQL VARBINARY(16)).

解决方案

ActiveRecord::Base.connection.execute("INSERT INTO ips(start) VALUES(inet6_pton('1.2.3.4'))")

这篇关于使用SQL函数的插入/更新中的ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆