0

I get an error

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%booked%)

How can I solve this?

Model

scope :with_type, lambda { |type|
   where("LOWER(reservations.message) LIKE %#{type}%")
}

Sql statement on server

SELECT  `reservations`.*
FROM `reservations`
LEFT OUTER JOIN `users` ON `users`.`id` = `reservations`.`from_id`
WHERE (`users`.`access_level_id` != 1)
AND `reservations`.`id_to` IS NULL
AND (LOWER(reservations.message) LIKE %booked%)
ORDER BY reservations.created_at desc LIMIT 10 OFFSET 0)
0

1 Answer 1

2

SQL's LIKE operator takes strings on both sides so the SQL you want to produce is:

LOWER(reservations.message) LIKE '%booked%'

i.e. %booked% in single quotes. The easiest way to do that is to use a placeholder in your scope:

scope :with_type, ->(type) { where('LOWER(reservations.message) LIKE ?', "%#{type}%") }

That puts the string interpolation in Ruby and hands that string to where to quote it so you're also protected from injection issues.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.