Reputation: 1269
I have an application using Ruby on Rails where a user will be providing a connection string and will be requesting data from their database. I found a link that get's me part of the way and thought to post a question to see if anyone has experience in this. Here's something I've found:
def fetch_value
sql = ActiveRecord::Base.connection();
sql.execute "SET autocommit=0";
sql.begin_db_transaction
id, value =
sql.execute("SELECT id, value FROM sometable WHERE used=0 LIMIT 1 FOR UPDATE").fetch_row;
sql.update "UPDATE sometable SET used=1 WHERE id=#{id}";
sql.commit_db_transaction
value;
end
I'm writing this application to be similar to phpmyadmin but in rails. I don't know the structure of the tables, but I would like to essential return json results of the queries they specify.
What I need is to be able to create a connection, retrieve a list of results and output the results in json without knowing too much. Any help would be appreciated.
Upvotes: 1
Views: 643
Reputation: 6484
Active Record is a Object Relational Mapping library which means it maps (known) tables to objects in Ruby. Active Record does expose ways to get directly to SQL, as you've done in your example, but it is not a 'normal' use case. In this case you would need something that is more generic.
You could have a look at Sequal. It is a Ruby library that abstracts SQL syntax away but not quite to the extend of Active Record where you have a strict table to object mapping.
If Sequal still gets in the way you can use the raw MySql Ruby module. Very powerful but should probably be a last resort because of the manual work you have to do.
Also remember that you could still use Active Record for your application database - perhaps users need to register and sign up. Sequal or the Mysql Ruby module is then used where your users enter db details directly.
Upvotes: 1