Rails 3.2, what's the best way to associate/lookup to a legacy table belonging to another schema? - ruby-on-rails

New Rails guy here...
I have a SimpleForm model which belongs to a Parts table belonging to another schema that's not Rails application.
What's the best way to model this association so that my form can do a lookup of the Parts table for part_id and the model can validate the part_id foreign key against the legacy Parts table?
possibilities:
create a database view and activerecord model in rails app?
create a readonly model with query/connection to Parts table?
Please be specific, as I really don't know much within Rails.
I am using Rails with Oracle and Windows, so any solution has to work with these.
Thanks in advance!

I ended up using database migration to create a database view and created readonly model for it.
In my SimpleForm, setup belongs_to relationship to the new Parts model and validates_presence_of to enforce the foreign constraint on inserts and edits.
Looks like this is pretty good way to do readonly foreign key reference by granting only "select" permission to legacy table and also setting Rails model to readonly.

Related

How to convert an attribute to a reference in rails

I am new to ruby on rails and I am working on an existing project in which I think some of the attributes of the models should be changed to be independent models; then they should referenced in the original models. What are the needed tasks to do this? Should I first remove those columns and then generate new models based on the attributes or there is easier way?
Thanks in advance.
There is no way to automatically spin off attributes into a separate model definition.
If there's existing data that you want to preserve, then create the new model with a migration and with a foreign key to the original model, and then write code to transfer the data.
Primary.each do |p|
p.secondary = Secondary.new
p.secondary.attribute_1 = p.attribute_1
p.secondary.attribute_2 = p.attribute_2
p.secondary.save
end
Then delete the primary attribute_1 and attribute_2 columns
If there is no existing data you need to preserve, then just create the new model and delete the old attributes using migrations.

In Rails should i generate a model to contain simple plain list?

I'm currently building a web-page with Ruby on Rails. Im creating A data model that works as follows: Project has many Milestones and milestone has many goals
Example:
Project.milestones.goals
So I generated a model for Project and a model for milestones but generating a model for list of goals seems like big and unnecessary.
Should I generate a model for goals or is there something else that would fit more for this purpose?
It all comes down to this question: Goals need to be persisted on your database?
If the answer is yes, then you must create a model that inherits from ActiveRecord::Base, and if the answer is no, you could create a model, that don't have the need for persistence methods of ActiveRecord, but acts like an Enum, having static values and stuff.

Rails 3 Polymorphic Association between one MongoMapper model and one/many Active Record model/s

I have a Record model (Active Record) that stores some custom logs.
Record is in polymorphic association with all the other model in my app, and I can effectively log what I want hooking my Record methods in the other controllers.
What I need:
To have the logs in a separate database.
So I have to:
Be able to manage two different databases in my apllication (one is Postgres/ActiveRecord and the other one is MongoDB/MongoMapper)
Generate a polymorphic association between my Record model, now with MongoMapper, and the rest of my Active Record models.
That way I can persist my logs to the MongoDB database.
Thanks.
Yes this can be done.
To create a polymorphic association you need both the class and an id. Idiomatically the fields will be named <assoc>_type and <assoc>_id‡. You will need to do some wiring up to make everything work.
Create a MongoMapper::Document Class with the keys <assoc>_type and <assoc>_id with the correct types (I believe MongoMapper allows Class as a key type) along with any other keys you may need.
Define the method <assoc> and <assoc>=
def assoc
assoc_type.find(assoc_id)
end
def assoc=(input)
assoc_type = input.class #STI makes this more complicated we must store the base class
asspc_id = input.id
end
Possibly add a method to your ActiveRecord models allowing them to access you MongoMapper logging class. If there are a lot, you may want to build a module and include it in all the classes that need that kind of functionality.
‡ replace with something meaningful for you application like 'reference' or 'subject'

Rails Generate Model from Existing Table?

I'm very new to the rails framework and want to know how to generate a model based on an existing table. For example, I have a table named person and want to generate the model based on the columns from that table. However, whenever I use "ruby script/generate model Person --skip-migration it creates an empty table named people and creates the model after that. Is there a way to generate a model after a table named person?
Thanks.
Rails is very opinionated, so if you have a table called "person" and you want the corresponding model to be called Person, you need to tell Rails explicitly not to be so clever (otherwise, it will assume that it needs to look for the plural of the model name for the table name).
class Person < ActiveRecord::Base
set_table_name 'person'
end
If your table's primary key isn't called "id", then you'll need to specify that, too...
set_primary_key 'person_id'
You may also need to specify a different autoincrement sequence name, depending on your database.
There's not a way that I know of to automatically generate a model from an existing legacy table, but this should get you most of the way there.

What is Ruby on Rails ORM in layman's terms? Please explain

I am having trouble understanding ORM in Ruby on Rails. From what I understand there is a 1:1 relationship between tables/columns and objects/attributes. So every record is an object.
Also what exactly is a Model? I know it maps to a table.
What I'm really after is a deeper understanding of the above. Thank you in advance for your help
I'm a Web developer going from PHP to Ruby on Rails.
"From what I understand there is a 1:1 relationship between tables/columns and objects/attributes. So every record is an object."
That is not exactly correct, unless you use the term "object" very loosely. Tables are modelled by classes, while table records are modeled by instances of those classes.
Let's say you have a clients table, with columns id (autonum) and name (varchar). Let's say that it has only one record, id=1 and a name="Ford". Then:
The DB table clients will map to the model class Client.
The record will map to a model instance, meaning that you have to create the object and assign it to a variable in order to work with the record. The most common way would be to do ford = Client.find(1)
The two columns of the table will map to methods on the ford variable. You can do ford.id and you will get 1. You can do ford.name and you will get the string "Ford". You can also change the name of the client by doing ford.name = "Chevrolet", and then commit the changes on the database by doing ford.save.
"Also what exactly is a Model? I know it maps to a table"
Models are just classes with lots of very useful methods for manipulating your database. Here are some examples:
Validations: Besides the typical db-driven validations ("this field can't be null") you can implement much complex validations in ruby ("this field must be a valid email" is the most typical one). Validations are run just before you invoke "save" on a model instance.
Relationships: The foreign keys can also be mapped onto models. For example, if you had a brands table (with its corresponding Brand model) associated via a foreign key to your ford client, you could do ford.brands and you would get an array of objects representing all the records on the brands table that have a client_id = 1.
Queries: Models allow you to create queries in ruby, and translate them to SQL themselves. Most people like this feature.
These are just some examples. Active record provides much more functionalities such as translations, scoping in queries, or support for single table inheritance.
Last but not least, you can add your own methods to these classes.
Models are a great way of not writing "spaguetti code", since you are kind of forced to separate your code by functionality.
Models handle database interaction, and business logic
Views handle html rendering and user interaction
Controllers connect Models with Views
ORM in Rails is an implementation of the Active Record pattern from Martin Fowler's Patterns of Enterprise Application Architecture book. Accordingly, the Rails ORM framework is named ActiveRecord.
The basic idea is that a database table is wrapped into a class and an instance of an object corresponds to a single row in that table. So creating a new instance adds a row to the table, updating the object updates the row etc. The wrapper class implements properties for each column in the table. In Rails' ActiveRecord, these properties are made available automatically using Ruby metaprogramming based on the database schema. You can override these properties if required if you need to introduce additional logic. You can also add so-called virtual attributes, which have no corresponding column in the underlying database table.
Rails is a Model-View-Controller (MVC) framework, so a Rails model is the M in MVC. As well as being the ActiveRecord wrapper class described above it contains business logic, including validation logic implemented by ActiveRecord's Validation module.
Further Reading
Rails Database Migrations guide
Rails Active Record Validations and Callbacks guide
Active Record Associations guide
Active Record Query Interface guide
Active Record API documentation
Models: Domain objects such like User, Account or Status. Models are not necessarily supported by a database backend, as for example Status can be just a simple statically-typed enumeration.
ActiveRecord:
Provides dynamic methods for quering database tables. A database table is defined as a class which inherits ActiveRecord class (pseudo-PHP example):
class User extends ActiveRecord {}
//find a record by name, and returns an instance of `User`
$record = User::find_by_name("Imran");
echo $record->name; //prints "Imran"
//there are a lot more dynamic methods for quering
New records are created by creating new instances of ActiveRecord-inherited classes:
class Account extends ActiveRecord {}
$account = new Account();
$account->name = "Bank Account";
$account->save();
There are two pieces here: the ORM and Rails's MVC pattern. ORM is short for "object-relational mapping", and it does pretty much what it says: it maps tables in your database to objects you can work with.
MVC is short for "model-view-controller", the pattern that describes how Rails turns your domain behavior and object representations into useful pages. The MVC pattern breaks down into three chunks:
Models contain a definition of what an object in your domain represents, and how it is related to other models. It also describes how fields and relationships represented in the object map to backing stores (such as a database). Note that, per se, there's nothing about a model which prescribes that you have to use a particular ORM (or even an ORM at all).
Controllers specify how models should interact with each other to produce useful results in response to a user request.
Views take the results created by controllers and render them in the desired way. (By the time you get to your view, you should mostly know what's being rendered, and there should be very little behavior happening.)
The definition from Wikipedia:
Object-relational mapping (ORM, O/RM,
and O/R mapping) in computer software
is a programming technique for
converting data between incompatible
type systems in relational databases
and object-oriented programming
languages. This creates, in effect, a
"virtual object database" that can be
used from within the programming
language.
From a PHP view it will be in the following way(via example)
Connect to the database and get some row from posts table.
Turn that row to an object with attributes like those in the table columns.
If the posts has comments in comments table, you can also do post.comments and you get the comments also as an array of objects as well.
You can define relationships between tables like saying: Posts has_many Comments, a Comment belongs to a post and so.
So basically you are not working with database rows, instead you turn those rows and their relationships to objects with composition or inheritance relationships.
In layman's terms.
A Rails Model is proxy to a table in the database. These models happens to be Ruby classes.
The objects of these classes are proxies to rows in the table of which this model is a proxy.
Finally the attributes of these objects are proxies to the column data for that particular row.
Above is actually the Rails ActiveRecord ORM.
1:1 is not quite correct, since there is object-relation impedance mismatch.

Resources