Connecting to external database the idiomatic way in RoR? - mysql

I am creating a RoR app, and need to connect to my company's MySQL database (which has nothing to do with this app in itself) to gather some data and report it through the RoR app. What is the idiomatic way to connect to this database? I'll just be running some fairly lite select queries off of it, however they often involve table joins. Should I just connect as through this were not a RoR app?

If your queries are mostly bound to single tables or utilize only a few joins, you can actually define models for them. It would seem that allowing ActiveRecord to operate on them may be the most idiomatic method to do it inside Rails.
First, define the company database in your database.yml
class ExternalDbTable
# Connect to the db
establish_connection :connx_from_database_yml
# Define table if this query is bound to a single table
set_table_name 'ext_db_table'
set_primary_key 'pk_column'
end
From there, you can define named_scopes as you would with a Rails model and basically enjoy all ActiveRecord's benefits. If you don't have to access more than a handful of tables on the external db, you can create models for each and define has_many/belongs_to relationships as you normally would in ActiveRecord. However if it is a large number of tables and you have the ability to create a view on the external database, you can create a model pointed to the view which performs the joins for you. Then define named_scopes against the view as necessary.

Related

MySQL Workbench 6 - difference in creating database / schema as a model and within a MySQL Connector

I was rooting MySQL Workbench and I had a TILT.
In MySQL Workbench initial screen there are two things I did not understand.
When creating a connection and access this, I have the option of creating schemas / databases and create your tables, scripts, etc. .. If I create a database named example, I only have the option to create the tables by script, not by EER diagram.
Returning to the MySQL Workbench initial screen, there is also the option of creating a model (for me it is a schema / database in the same way). If we create a model named example, as in the previous item within this you can create scripts, views, tables, and have the distinction of creating EER diagrams.
What I wanna know is:
Why there are options of create schemas / databases as models and within MySQL Connections?
why I can create schemas / databases with the same name in both options to create schemas / databases (MySQL Connectors and Models) without naming conflicts happen?
If they are the same thing, why when I create a model MySQL Connector does not synchronize automatically to recognize the model?
If they are the same thing, that I can create EER Diagram for schema / database in the Model and not in MySQL Connector?
Thanks to anyone who can answer me these questions.
You started from the wrong premise. Models and connections are two completely different things (why would there be different sections in MySQL Workbench if not?).
Via connections you can reach a server and work on it. Create users, retrieve data, create db objects etc.
Modeling is however the task to design a database structure. All the objects you create only exist within that model. You can design your structure from a higher level of view instead of going down to the pure SQL (which you can too, if you want). Nothing reaches a server until you either forward engineer your model or synchronize it to that server. The first is simply creating all the objects as you designed them, the latter is a two-way 'merge', that is, a diff is generated between the model and the server content and changes are applied to make the structure on the server be the same as in the model and vice versa.
Understanding that fundamental difference answer all your questions above.

mysql worbench. how to create database if I have model

I am novice in mysql server.
I use latest version of worbench.
using designer I created model:
But in databases I don't see my model:
I bad in mysql termins But I want to get so thing where I can insert data to Student and Group tables.
Modeling is more an abstract work to develop your schema structure systematically. It helps you to define needed objects, their relationships, users etc. that are needed. A model however has no data or any real representation of the objects it contains.
In order to use the objects you have to bring them on a real server. There are different ways to accomplish that, for instance you can forward engineer your model to a server (see Database menu). You have to select (or create) a connection to a server of your choice and let MySQL Workbench generate and apply a script to generate all the objects. Once this is done you can open those objects in the SQL IDE to fill them with data or work on them.
MySQL Workbench also has a synchronization feature that you can use after forward engineering. It's a two-way sync that allows to apply changes in your model to the schema objects on your server and also take over any changes made there into your model. All that can be fine tuned in the sync wizard.

'Connect' a rails app to an already existing MySQL DB?

So in my company we are slowly moving to Rails instead of PHP(Code Igniter to be precise).
So, our actual PHP App is using a Mysql DB and I'd like to connect a new Rails app to this DB but meanwhile our PHP is still running, so I can't change the DB.
I don't really know where I should start to use all the rails features (Or at least as much as possible).
There shouldn't be any harm in connecting your rails app to an existing database. You will need to watch for anything that goes against rails conventions (table names are plurals of models, for example) and either change the database (and your php app) or program around the problem in rails.
But the first step is simply to connect to the database and make models for the existing tables and see what works and what doesn't.
After that, post here with any specific problems.
As a suggestion, take a backup of your database and start out programming against that to build your application and be sure everything works safely.
Well, first of all you should setup the connection in config/database.yml and then start to generate the scaffolding (models, views and controllers) table by table (check the Rails generate command). I am not really sure if you have already generated the app though. Anyway, the generator will also generate a migration script that you obviously dont want to run as the db is already there.
Hope this helps a bit.
Anyway, some resources:
http://guides.rubyonrails.org/
http://railsapps.github.io/
There are two aspects of a Rails app to consider for this scenario:
1: the database connection
Simply put the credentials for this database into database.yml.
A model like "User" will by default attempt to find records and attribute definitions in a table called "users". ActiveRecord will assume there's an auto-incrementing integer primary key on each table. When saving records, it will attempt to write to columns called created_at and updated_at. Those are a few things to be mindful of when making and using the connection.
2: the database migrations
Rails uses migration files to manage a sequence of changes to the database structure. Under normal conditions, someone building a Rails app will be starting with an empty database.
In the case of an existing database, I would recommend making a migration something like:
class BuildLegacyDbStructure < ActiveRecord::Migration
def up
Mysql2.connection.execute_some_sql_file( # made-up function
Rails.root.join('path', 'to', 'file')
)
end
def down
# reverse those changes; bring DB down to blank state
end
end
Another option would be to disable Rails/ActiveRecord's migration-based management of the database entirely. For example Rails will generate a migration when you generate a new model. So if you have an existing users table in your PHP app, and you'd like to make a rails model to use this table, you'd run something like rails generate model User --no-migration.

Read similar tables from multiple MySQL databases using WS02

We got an application wherein multi-tenancy is implemented by having a unique database (MYSQL) for each tenant. The table structures are the same. I got a requirement to list all expiring products for each of the tenants, and I was wondering how can I incorporate all those in one data web service in WSO2? I know that I can create a query with the database prefixing the table:
eg. select DB1.products.id, DB1.products.name from DB1.products
Do I need to define a data source for each database (100+ tenants), and can I specify the database name as an input variable in the data service operation? ie. select ?.products.id, ?.products.name from ?.products
Thank you for your help.
Cheers,
Erwin
If your intention is to have a generic data service that would retrieve those tenant specific information from those database dedicated to each tenant, as I see, the most cleanest way to achieve this would be by generifying your SQL queries and making the used datasource dynamically discoverable.
Since you're using 100+ tenants(WOW that's a huge number :)) obviously you might be having 100+ databases created for those tenants too. So, you would need to create a carbon datasource with the same name in each tenant (let's say "testDS") wrapping the tenant specific database configurations such as JDBC URL, credentials, etc. Next, if you've come up with your dataservice configuring the used datasource to be the aforementioned datasource, at runtime, it would correctly pick up the appropriate tenant specific datasource as the datasource feature completely supports multi tenancy. That would prevent you from passing the database name, etc to the SQL query and make your data service configuration more clean, generic thereby making it more maintainable.

Putting Rails over top of an existing database

I have an application written in PHP/MySQL (symfony, to be specific) that I'd (potentially) like to rewrite in Rails. I know how to create scaffolding for tables that don't exist yet, but how do I get Rails to read my existing table structure and create scaffolding based on that?
Update: it turns out I can run the following command to get Rails to generate models for me:
rails generate scaffold Bank --no-migration
But it doesn't give me forms. I would prefer something that gives me forms.
The answer is db:schema:dump.
http://guides.rubyonrails.org/migrations.html
The easiest route is to pretend that you are writing a fresh app with a similar database schema - you can then create your models and migrations with the old schema in mind, but without being restricted by it. At a later stage, you can create a database migration script to copy all the old data into the new schema.
I'm doing this right now. The benefit of this approach is that you can take advantage of all of the rapid development tools and techniques provided by Rails (including scaffolds) without being slowed by trying to retrofit to the exact same schema.
However, if you do decide that you don't like this approach, and you do need to map your new models to existing tables, there are a number of configuration options provided by active record where you can override the convention over configuration naming patterns and map model names to tables names, set oddly named ID fields etc. For example:
class Mammals < ActiveRecord::Base
set_table_name "tbl_Squirrels"
set_primary_key :squirrel_id
end
The above will help Rails attempt to read your existing table, but success will depend upon how well the existing table structures matches Rails conventions. You may have to supply more configuration information to get it to work, and even then it might not work.
Finally, it may be worth considering the use of DataMapper which I believe is more suited to existing brownfield databases than ActiveRecord, because it allows you to map everything, but of course you will need to learn that API if you don't already know it.