RoR:在控制器中执行SQL

RoR: Execute SQL in controller

在RoR中,在controller中,我们可以看到如下几行:

def index
    @books = Book.all
end

如何将 @books = Book.all 替换为实际的 sql 查询,例如 select * from book

我尝试了类似下面的方法,但没有成功:

def index
    sql = 'Select * from books'
    @books = ActiveRecord::Base.connection.execute(sql)
end

在浏览器中,我看到这条错误消息:

#Hash:0x00007f8dbae412f0 的未定义方法“标题”

Active Record 的 find_by_sql 方法是可行的方法。

def index
    @books = Book.find_by_sql('Select * from books')
end

参考:https://guides.rubyonrails.org/active_record_querying.html#finding-by-sql