How to run simple MYSQL query using rails

13,197

Solution 1

movie_title = 'Planet of the Apes'
sql = "SELECT * FROM movies WHERE title = #{ActiveRecord::Base.sanitize(movie_title)}"
ActiveRecord::Base.connection.execute(sql)

Solution 2

Just use ModelName.find_by_sql("your sql query") in your console.

Solution 3

Config the database connection in

/config/database.yml

In Controller,

def connect_and_fetch
    result_obj =  ActiveRecord::Base.connection.execute("select column from table")
    @rows = []
    index = 0
    result_obj.each do |row|
      @rows[index] = row
      index += 1
    end
end

In html view,

Result : <%= @rows%>
Share:
13,197
Admin
Author by

Admin

Updated on July 29, 2022

Comments

  • Admin
    Admin almost 2 years

    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