Use SQL functions for insert/update in ActiveRecord

浪尽此生 提交于 2019-12-23 17:38:13

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/7148945/use-sql-functions-for-insert-update-in-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!