Best way to escape single quotes

Hi guys,

What is the best way to escape single quotes?

For example if I have a blog app and in that a post model with title and body as attributes. How can I save a post with title “My Dog’s Fur”?


@manishval If i understand you correctly, you want to save input from your form into your model…right? If that’s the case, you don’t have to worry about escaping single or double-quotes: just store the field (something like params[:post][:title] into your model as you would normally do. You’ll need to worry about escaping quotes when if you’re defining stuff in ruby. For example:

  title = "My Dog's Fur"

is OK because the single quote is inside a double-quoted string. You only need to escape something like this:

  title = 'My Dog\'s Fur'

Interestingly, this:

  title = 'My Dog''s Fur'

doesn’t work (at least in 1.9.3) as it looks to ruby like two separate concatenated strings.

Hope that helps…

I think the problem is in postgres. For example when I got to create a post with the title “My Dog’s Fur”, I get the following error.

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error at or near "s"
LINE 1: ...NT(*) FROM "users"  WHERE (lower(username) = 'my dog's fur')

You’re absolutely right. I’m not sure how you handle that with Postgres… and SQL Server would have the same problem as it uses single quotes to enclose text strings.