Home > Enterprise >  RoR: Execute SQL in controller
RoR: Execute SQL in controller

Time:01-20

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

CodePudding user response:

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

  •  Tags:  
  • Related