Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RoR: Execute SQL in controller

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading