Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run simple MYSQL query using rails

I want run a simple MYSQL query using rails

Select movie-title, movie-director from moving order by rating desc limit 5;

I don't want all the overhead creating models. I just want to run the query.

What is the best way to do this?
I cannot even connect

Here is my the code from my controller

ActiveRecord::Base.establish_connection ({
:adapter => "mysql2",
:host => "some-rds.amazon.com",
:username => "root",
:password => "root",
:database => "blah"})

This will generate this error ActiveRecord::ConnectionNotEstablished

thanks

like image 358
user2770152 Avatar asked Sep 11 '13 20:09

user2770152


People also ask

Can you use MySQL with rails?

Ruby on Rails uses SQLite as its database by default, but it also supports the use of MySQL.

How do I run a MySQL query in terminal?

To access a specific database, type the following command at the mysql> prompt, replacing dbname with the name of the database that you want to access: Copy use dbname; Make sure you do not forget the semicolon at the end of the statement. After you access a database, you can run SQL queries, list tables, and so on.


1 Answers

movie_title = 'Planet of the Apes'
sql = "SELECT * FROM movies WHERE title = #{ActiveRecord::Base.sanitize(movie_title)}"
ActiveRecord::Base.connection.execute(sql)
like image 74
Zabba Avatar answered Oct 19 '22 23:10

Zabba