Using Colon (:) with Rails find_by_sql

Asked 2 years ago, Updated 2 years ago, 31 views


using Rails find_by_sql SomeModel.find_by_sql(["SELECT1 FROM ip_addrs WHERE ip_addr=':FFFF'ANDid=:id", {id:1}])
I'd like to do a case where I want to include a colon in SQL and replace the parameter name, but the colon in SQL is considered a replacement and I get an error

Isn't there an escape method that distinguishes a regular colon from a colon for replacement?

ruby-on-rails ruby

2022-09-29 22:32

1 Answers

SomeModel.find_by_sql(["SELECT1 FROM ip_addrs WHERE ip_addr=CONCAT(':', 'FFFF') ANDid=:id', {id:1}])

You can avoid the appearance of [a-zA-Z] immediately after a colon by rewriting it to string concatenation grammar at the SQL layer as shown in
ActiveRecord::Sanitization::ClassMethods.replace_named_bind_variables does not match the regular expression, thus protecting colons in SQL strings from destruction by rails


2022-09-29 22:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.