3

I want to execute this query in rails app

   Video.where("category= 'film' AND grant = 1").order('created_at DESC').page(params[:page]).per_page(10)

here grant stores an integer value.

and I am getting following 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 'grant = 1) ORDER BY created_at DESC LIMIT 10 OFFSET 0' at line 1: SELECT  `videos`.* FROM `videos`  WHERE (category= 'film' AND grant = 1) ORDER BY created_at DESC LIMIT 10 OFFSET 0

thanks in advance

3 Answers 3

5

The problem is with grant. GRANT is a reserved word in MySql. You should use back-ticks around them.

Video.where("category= 'film' AND `grant` = 1").order('created_at DESC').page(params[:page]).per_page(10)

will do the job i guess. Refer Reserved Words

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

2 Comments

A more Rails-ish implementation would use where(category: "film", grant: 1).
what if we want to use OR instead of AND ?
4

Try this ..

@videos=Video.where(:category => 'film',:grant => 'yes' ).order('created_at DESC').page(params[:page]).per_page(10)

2 Comments

thanks, it worked for me... but i have no clue why other queries is not working.
also i changed :grant => 'yes' to :grant => '1'. since my "grant " stores integer value.
0

Check this:

Video.where("category = ? AND `grant` = ?", "film", 1).order('created_at DESC').page(params[:page]).per_page(10)

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.