jeudi 21 juillet 2016

what's the difference between by passing a symbol and string in where clause with joins

I have two models User and Book. User have username and email field, Book have author and title field. When I am using joins to get the users based on associated data with conditions passed in where clause, I am getting different results

  1. When I run this
User.joins(:books).where('author = ? ','xxxx')

Mysql query generated is :

"SELECT `users`.* FROM `users` INNER JOIN `books` ON `books`.`user_id` = `users`.`id` WHERE (author = 'xxxxx' )"

gives me the user whose book include xxxx author whereas

  1. When I run this
User.joins(:books).where(author: 'xxxx')  

Mysql query generated is:

"SELECT `users`.* FROM `users` INNER JOIN `books` ON `books`.`user_id` = `users`.`id` WHERE `users`.`author` = 'xxxx'"

gives Mysql2::Error: Unknown column 'users.author' in 'where clause': SELECT users.* FROM users INNER JOIN books ON books.user_id = users.id WHERE users.author = 'xxxx' ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'users.author' in 'where clause': SELECT users.* FROM users INNER JOIN book ON book.user_id = users.id WHERE users.author = 'Dan Brown'

My question : is when I am passing a string encapsulated field and value in where clause it gives me result but when I pass a symbol in where clause it gives me mysql unknown column error. So how does ruby interpreter know from where to fetch data in symbol passing and string passing

Aucun commentaire:

Enregistrer un commentaire