wizztjh
wizztjh

Reputation: 7041

Ruby on Rails to create and access MySQL variable

How to use Ruby on Rails to do this?

mysql> SET @t1=1, @t2=2, @t3:=4;
mysql> SELECT @t1, @t2, @t3, @t4 := @t1+@t2+@t3;

Upvotes: 4

Views: 1484

Answers (1)

wuputah
wuputah

Reputation: 11395

Use ActiveRecord::Base.connection:

>> ActiveRecord::Base.connection.execute("SET @t1=1, @t2=2, @t3:=4;")
 => nil 
>> ActiveRecord::Base.connection.select_one(
    "SELECT @t1, @t2, @t3, @t4 := @t1+@t2+@t3;")
 => {"@t1"=>"1", "@t2"=>"2", "@t4 := @t1+@t2+@t3"=>"7", "@t3"=>"4"} 

For more methods you can use on this class, see the documentation here.

You can also call the connection method on any ActiveRecord class you have defined. For instance, if you have a model called Post, you can use Post.connection.execute("sql").

Upvotes: 6

Related Questions