简体   繁体   中英

Convert SQL Statement to Rails ActiveRecord

I want to convert the following into Rails Ruby code:

SELECT * FROM ALBUMS
WHERE TITLE='Greatest Hits'
AND ARTIST='The Beatles';

SELECT COUNT(ID) FROM ALBUMS
WHERE TITLE='Greatest Hits'
AND ARTIST='The Beatles';

For the first, I've read about the pluck method in Ruby, but I don't know how to pluck given multiple limitations, in this case, not just title, but also artist.

For the second, I want to just count how many occurrences of title and artist being the same.

Please help? My best source: http://apidock.com/rails/ActiveRecord/Calculations/pluck

SELECT * FROM ALBUMS
WHERE TITLE='Greatest Hits'
AND ARTIST='The Beatles';

Assuming a model named Album

Album.where(title: "Greatest Hits", artist: "The Beatles")

For the second

SELECT COUNT(ID) FROM ALBUMS
WHERE TITLE='Greatest Hits'
AND ARTIST='The Beatles';

Use the count method.

Album.where(title: "Greatest Hits", artist: "The Beatles").count(:id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM