Doing SQL queries in Rails with Variables - Converting a PHP/Codeigniter Application - mysql

I'm converting a PHP app written in CodeIgniter to Rails.
Due to the size of the application and the inability to makes change to the schema, I'm not interested in making models for each entity.
I want to be able to do CodeIgniter style queries like this (Supply a pre-written query and associated variables):
query("SELECT * FROM posts WHERE id = ?", id)
and get a result back.
I know that it's highly suggested to use models and do it "the rails way", and I definitely plan to for my next application that I write from scratch in Rails, but for this project I want to avoid the ORM and just have the ability to do direct queries using the database connection.
What would be the best way to do this?

I hate myself for not having the willpower to not answer this question, so just quickly:
Use ActiveRecord#find_by_sql

Related

Ruby: Exposing MySQL query ability to users via RESTful API

There are similar posts like this on the internet, but they seem to be targeted towards lower level languages like Java. NetBeans for example seems to have this kind of functionality.
Here is what I want to do:
I have a large dataset of items. I want to create a RESTful API that would enable my users to perform complex queries to retrieve data from the MySQL database on my backend.
The API needs to be able to:
SELECT a table to retrieve values from
Be able to use common MySQL aggregate functions such as COUNT, SUM,
and AVG on the results
Create WHERE conditions
Security is not an issue as this my simply an MVP for now. On a future iteration I will take security into consideration. Are there any Ruby gems which provide a framework for constructing this kind of system?
I am open to using either Sinatra or Rails for this system.
Maybe this can help you:rails-api
Rails::API is a subset of a normal Rails application, created for
applications that don't require all functionality that a complete
Rails application provides. It is a bit more lightweight, and
consequently a bit faster than a normal Rails application. The main
example for its usage is in API applications only, where you usually
don't need the entire Rails middleware stack nor template generation.
or you can use grape gem.

SQL Files and Ruby on Rails

So I'm kinda new with Ruby on Rails. In one of my Database classes the teacher asked us to create a simple application using any tool I liked. The app just has to have the ability to get new users, let users make appointments and add patients (it's for doctors), all that just enter information to the database and quering the database for information.
The problem is that in the specifications of this project says that every interaction with the database has to be done in "Raw SQL", so I can't use the Ruby On Rails utilities. I have been working with this framework for about six months, so I'm familiarized with it, and I know how to make the "Raw SQL" for the seeding of the database, and the queries, but I don't know how to start the project from my database.sql file, where I create the schema and all the tables.
This can be with any DBMS, I currently have a script for sql server and mysql.
How can I create my project using the sql file to create the database instead of using rails migrations?
Thanks in advance!
By "Raw SQL" does your teacher mean all the SQL, including the CREATE TABLE statements? Or just the SELECT statements? You can do both, raw, in Rails, but can you use standard Rails migrations?
Rails is like learning assembler by learning C. You learn assembler better when not lost in an endless sea of it. Rails wraps up relations so you don't need to spend all day writing redundant JOIN clauses.
Here's the answer to the "raw SQL?" FAQ in Rails: http://apidock.com/rails/ActiveRecord/Querying/find_by_sql . I would wrap that in a cute logger method that writes each SELECT statement to a formatted file, so you can turn that in as your homework. But you can tell I didn't do very well in school...

Ruby on Rails3 and MySQL query best practices

I'm trying to transition from PHP to Rails and was wondering what the best practices are. I have all the data I need in MySQL and would like to make simple queries and display them using the kinds of niceties afforded by ActiveRecords. I'm familiar with the MVC paradigm and am trying not to rely on my knowledge of PHP, but how, for example, would I be able to do the kinds of things I used to do with:
$query = mysql_query("Select * from table where name = 'blah');
if I already have that data (I can see generating a scaffold if I didn't have pre-existing data). Do I create a scaffold and then import my data into it? or do I write raw MySQL queries in Ruby?
Thanks!
First, remember that Rails is a web dev framework, not a scripting language like PHP. Ruby is the scripting language. PHP has frameworks as well, but just wanted to make sure you realize the difference between the one and the other.
Most basic and medium-complexity queries in Rails are handled via the ActiveRecord methods and helpers. You'll find that you'll be writing much less actual SQL, as that is generally abstracted away into the framework.
For instance, assuming the name of your model is City, the equivalent of your query in Rails would be:
City.find_all_by_name('blah')
How does this work? When you create a model in Rails you usually subclass ActiveRecord::Base. Built into that class is a plethora of functionality that, for one thing, examines your data table and builds dynamic finders for each of the fields and combination of fields on the table.
Since you already have all the data, you're going to be overriding some of the conventional functionality of Rails in order to get everything working. For instance, Rails assumes by convention that there is a primary key field named "id". Also, Rails assumes that the table is named as the plural form of whatever the model class definition is. All of these things are defaulted by convention, but can be overridden. If you were building from scratch and following conventions, all this would sort of happen as a matter of course.
Based on your question, I think you need to spend some time with some basic Rails reading material and some specific info about ActiveRecord and Rails models, so that you can come up to speed on these major differences between Rails and standard PHP application. If you don't get that straight from the beginning, then you are going to build a lot of PHP-style Rails stuff and you won't be taking full advantage of what Rails and Ruby have to offer. In the end, you'll say "what did I do all that for, it's all the same."
If, instead, you try to start from the Rails Way of doing things, you'll find that Ruby and Rails offer a lot.
If you are working with an existing database then you are going to have a hard time forcing Rails to play nicely with it. Rails power (some might call it a weakness) is that it favors convention over configuration. In other words, it really expects you database columns to be structured a certain way. Stray from the convention and you lose all the reasons for using Rails in the first place.
When you start a new rails project and use the migrations rails makes sure that the structure is as it expects.
If you are moving an old project to rails then I would strongly suggest writing a function to import that data into a rails-created DB. This will save you a lot of heartache in the long run and will allow you to take full advantage of Rails' strengths.

Running arbitrary SQL queries in Ruby

I've just been tasked with automating a reporting task at work. Previously, someone would run large, arbitrary SELECTs on a MySQL database using a GUI tool, then use that same tool to export the results to CSV. Now I want to write a Ruby script to do this.
I know about FasterCSV in Ruby, but as far as SQL queries, I've only used ActiveRecord, where you're generally not writing the queries but using models and associations. The last time I wrote out complete SQL in code was when I coded PHP.
What's the most straightforward way to do this sort of thing in Ruby? Should I use ActiveRecord?
If you are writing a complex application, there is absolutely nothing wrong with using ActiveRecord. Especially since you are already comfortable with it.
If you are writing a quick script and don't want to bother with ActiveRecord, you should also check out the mysql and mysql2 gems.
I highly recommend Sequel. It has great documentation, active development, a thriving and helpful community, and it is (IMHO) simpler and better than ActiveRecord, especially for simple use cases like you appear to have.
You might want to start by reading the README, Cheat Sheet and Sequel for SQL Users.
I often find that in reporting engines you end up with complex queries processing large amounts of data and ORMs like ActiveRecord just don't cut it. Unless your reports are really simple, I think you'll want to use raw SQL (with a tool like Sequel) or call stored procedures.

Multiple Rails app, single MySQL database

I intend to have multiple Rails apps each for site.com, api.site.com, admin.site.com. All apps will access the same tables from one single MySQL database. Apps and database runs in the same server.
Is there any settings in Rails, ActiveRecord or MySQL that I need to be concerned about for above access scenerio? Thanks
Running: Rails 2.3.5, MySQL 5.0, Nginx, Passenger, RubyEE
This configuration tends to be quite difficult to maintain.
In every app, you would need to keep schema.rb and models in sync in order to use the same database. It means lot of duplication.
This isn't probably a good idea. Instead, you might want to design the application to meet one of the following scenario:
one Rails application which handles site.com, api.site.com and admin.site.com (why do you need separate app?)
multiple Rails applications, but just one interact with the db. The others uses the main application API (quite complex)
different apps with different purposes (for instance, you might want to use Sinatra + Datamapper for api.site.com)
The first option is probably the best one in most cases.
I answered similar question here. You can do it and sometimes it is reasonable.