Reputation: 2443
In RoR, in the controller, we can see lines as below:
def index
@books = Book.all
end
How can the @books = Book.all be replaced by actual sql query like select * from book
I tried something like below but I did not get it to work:
def index
sql = 'Select * from books'
@books = ActiveRecord::Base.connection.execute(sql)
end
In the browser, I am seeing this error message:
undefined method `title' for #Hash:0x00007f8dbae412f0
Upvotes: 0
Views: 1067
Reputation: 769
The find_by_sql method by Active Record is the way to go.
def index
@books = Book.find_by_sql('Select * from books')
end
reference: https://guides.rubyonrails.org/active_record_querying.html#finding-by-sql
Upvotes: 1