2

I have been looking on online everywhere for an answer with no luck. Where do I enter my query? In rails c? I know i must use ActiveRecord::base.connection but I am clueless where it must be run. Sorry if this is a foolish question.

davefogo
  • 93
  • 1
  • 9

1 Answers1

6

Rails uses an ORM called ActiveRecord to interface with SQL databases:

http://guides.rubyonrails.org/active_record_basics.html

The syntax is straight-forward and you can enter queries by opening up your rails console with rails console (abbreviated rails c).

For example, if I want to find all of the records in the Question table, I open my console and simply type Question.all:

irb(main):001:0> Question.all

...which translates to the following SQL query:

Question Load (4.2ms) SELECT 'questions'.* FROM 'questions'

If you want to execute raw SQL commands in the rails console, you would use ActiveRecord::Base.connection.execute(some_string) with the SQL as a string object.

You could write the SQL string as the argument directly or declare it beforehand as a variable:

sql = "some raw sql"
ActiveRecord::Base.connection.execute(sql)

Check out this question for more: Rails raw SQL example

Community
  • 1
  • 1
sixty4bit
  • 7,422
  • 7
  • 33
  • 57
  • So this means that if I need to enter an active record statement it would be ActiveRecord::base.execute (statement) ? What if it's a complex query? Is there a file I wrote down everything on and then load it on rails console? – davefogo Apr 01 '15 at 20:18
  • ah, I see. At first I didn't get that you want to execute raw SQL. In that case, you just use ActiveRecord::Base.connection.execute(sql_as_string). I will update my answer. – sixty4bit Apr 01 '15 at 20:21