Welcome to Working With Rails

 

Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
[Noob] How RoR handles data normalization
2 Posts
[Noob] How RoR handles data normalization

***NOTE: I am sorry if I am posting this in the wrong section, so please feel free to move this thread.

I have only lightly looked in to RoR for a couple months now. I stumbled upon something that seemed weird to me, but I am sure you guys can answer my questions pretty quickly.

It seems RoR does not normaliza data in the database, or at least from my understanding.

For example (probably not the best, but just go with it):

If I had a model called Fruit, that kept many stats on the fruit (fruit type, weight, cost, etc). I would probably have the fruit type as a integer that is a foreign key to another table. This other table would contain the columns (fruit_id, fruit_name).

From what I have learned about RoR, it would not create this second table, it would just store a string in the Fruit table ("apple", "banana"). This doesn't seem like the best way to handle this data.

What am I missing? Can anyone point me to a resource to understand this better?

Rails does not design your database for you. You're free to normalize/denormalize your data as you see fit. Rails has rich support for associations which allows easy access to your model's attributes, regardless of what table you store them in.

Update: It occurred to me that you may have come to this conclusion based on a discussion somewhere of Single Table Inheritance. In the event that you have multiple classes (models) that are all descendants of a common base class, then ActiveRecord will allow you to persist all of them in one database table, using a special column by default called (unsurprisingly) "type". The string representation of the class name will be stored there.

So, for example, you may have a table called fruits with columns color and type, then you could have a model that looked like:

class Fruit < ActiveRecord::Base end

and then stuff like:

class Apple < Fruit end

class Banana < Fruit end

class Orange < Fruit end

And so on. Each of these could have their own custom methods but they'd be stored in the same table. The type column would contain "Apple," "Banana," "Orange" and so on, but color would be whatever you set it to.

2 Posts
Login to add your message