将SQL语句转换为Rails ActiveRecord

时间:2015-12-06 01:27:42

标签: sql ruby-on-rails ruby activerecord

我想将以下内容转换为Rails Ruby代码:

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

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

首先,我已经阅读了Ruby中的pluck方法,但我不知道如何采用多种限制,在这种情况下,不仅仅是标题,还有艺术家。

对于第二个,我想计算一下标题和艺术家的出现次数是多少。

请帮帮忙? 我的最佳来源:http://apidock.com/rails/ActiveRecord/Calculations/pluck

1 个答案:

答案 0 :(得分:0)

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

假设名为Album的模型

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

第二次

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

使用count方法。

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