Rails Associations In Plain English : What I Wish I Had Known Before I Started

Ok, ok, I can’t hide. I am a huge Ruby on Rails fan. It’s been a couple of years that i knew about RoR existence, but i never actually got to learn more about it, never engaged myself to its internals. For years, i’ve been coding A LOT using PHP, mySQL, Smarty or other template engines, Pear and the likes. As much as i liked all these, the truth is ugly; they are too damn slow for a single programmer to work with.
RoR came as a shock to me. In the first days, i could not even believe that it would automatically do all these things for me. Convention over configuration and a steep learning curve for me, BUT, it comes with a prize. Fewer code, less time spend, more things done. And as in every business, we need to maximize profit using the less resources possible, right ?
Yes, RoR is Difficult to Learn but ..
..it is heavily worth it. My problem when learning Rails was that of conventions (surprise !). Even today, i still meet some new challenges in that area. However, after reading more and more about Rails, it feels more natural and easier to grasp. Literally every new Rails programmer struggles with conventions. Single name for models, plural name for database tables, find_by, the list seems endless.
For me, one of the most difficult things to handle was Rails Associations. Before telling you a few things about them, please never underestimate the power of the official resource on Rails associations. I would like to explain associations to you as i understand them, not with many technical stuff. All technical things are available online easily, but getting a good grasp on the topic means that you understand the mechanics; and i feel that this is much more important than enumerating things for you.
What is an Association ?
If you have been using a database management system (mySQL, Oracle etc.), you already know of database associations. As i promised, i will not go too technical, and only stress the important things. In short, there are just 3 types :
1. one to one -> A child has one mother
2. one to many -> A mother has many children
3. many to many -> Many students have many teachers
1. A child can only have one mother (in this planet). In Rails words, you would have a Mother model and a Child Model. It is important to remember that belongs_to refers to the model where the foreign key is set. This example would create the database tables : children(irregular plural form) and mothers. A child has_one :mother and a mother belongs_to :child. This means that the attributes of the two tables are like :
children(id, name, whatever ..)
mothers(id, child_id, name, whatever ..)
2. For the second example, everything, in terms of database tables(models) is exactly the same. The difference in that declaration is that a mother can have many children and not just one. Therefore, mother.children would be availabe, instead of just child.mother of the previous example.
3. A many to many relationship is a whole new different thing. To hold many to many information, you always need an intermediate table. The reason is the DRY (don’t repeat yourself) principle. If we just used a students and a teachers table, we would need to repeat a student id as well as a teacher id all the time. That leads to very bad database design. Instead, we need an intermediate table, say teachers_students, so that we now need to create :
students(id, name, .. )
teachers(id, name, .. )
teachers_students(student_id, teacher_id)
This way, you clearly see that a student and a teacher are just two static models, in the sense that they do not define whether a student has a certain teacher and vice versa. This information is hold by teachers_students. Now, in Rails, there are two ways to declare this association. The has_and_belongs_to_many declaration and the has_many => through declaration. But, what are really the differences ?
Has_and_belongs_to_many or has_many => through ?
If you ask me, i would always prefer the second method, mainly because of habit. However, it would be a good idea to know the differences, in case you are not sure of which one to use. Has_and_belongs_to_many creates a many to many association for you automatically, as long as you create the intermediate model. It’s important to notice that the intermediate model has to have the name of the two join tables in alphabetical order. That is, if you have students and teachers, the intermediate table has to be students_teachers (or you can specify the name explicitly). This is, once more, a convention used by Rails.
Has_many => through was the first Rails way to do a many to many association and i like it better due to the fact that more information is revealed through such a declaration. What you would like to say in this example is that a student can have many teachers and a teacher can have many students. Thus, how about :
teachers have_many :students
students have_many :teachers
After all, this is what we want to do. However, there is a problem here. Rails is not able to find the information needed to understand what the students of a teacher are, and vice versa. The reason is that this information is contained in the intermediate table. Therefore, as in has_and_belongs_to_many, we need to specify a third table. Since there is no convention here, let’s name this table classroom_members, instead of teachers_students (the attributes remain the same).
Our declarations now take their final form :
teachers have_many :students, :through => classroom_members
students have_many :teachers, :through => classroom_members
Now, Rails has everything. If we do a “teacher.students”, Rails will search the intermediate table, find the teacher students and return a related object.
Messing With :Through
I understand that through can be a bit confusing. Sometimes, you think : “Do I really need through here” ? The general golden to rule to make out whether you need through or not, is to think of what information you need, in order to execute an association. Let’s think of an example to illustrate that.
We need to create a new model, say Classroom, which defines some information about the classroom where teachers and students exist. If we needed to get all the students in a classroom, that a certain teacher handles, we would like to be able to do something like :
classroom.students — the classroom model is like classroom(id, teacher_id, … )
But the classroom mode only has information about teachers and not students. Luckily, this information that binds a teacher to a student is present to the classroom_members table. This is where through applies smoothly here :
classroom has_many :students, :through => classroom_members
Do you see the convenience here ? The teacher_id that is present in the classroom, is able to get us student information through another table, classroom_members. Hope that makes it a bit more clear to you.
Good column , I’m going to spend more time researching this subject
Your one-to-one example is misleading. “A child has one mother” is not a one-to-one relationship. It is one-to-many, because the relationship (as a whole) consists of one mother related to (potentially) many children.
You seem to be using “one-to-one” to describe just one direction of the relationship rather than the relationship as a whole. But that is not how it is commonly used as far as I know.
@Clay : You are potentially right, it’s a bit misleading, i may need to provide a better example. Of course the relationship depends on the way it’s defined in a particular problem, but for the most part yes, it’s most probably used as a one-many.
Would it not be more natural to construct is such that “child belongs_to :mother” and “mother has_many :children”?
@Ignatius : Yes, it could certainly be made like that and it’s most probably the way that most applications would want it to be.
Hey! I’m at work surfing around your blog from my new iphone
4! Just wanted tto say I love reading your
bllog and look forwaard to all your posts! Keep up the fantastic
work!
Touche. Outstanding arguments. Keep up the great spirit.
The process of ranking a website in search engines is actually
quite complicated though. com finds and tells stories of young Nigerians doing incredible
things. The added protection helps prevent the early wear and
tear on the tennis shoe.
With Ladbrokes skill games, you can readily play betting games right
from home or anywhere you want to. The site offers betting options such as
‘Bankers Bets’, ‘If Bets’ and ‘Reverse If Bets’ are all possible.
Never let the customer steam roll your company with their own agenda.
And I was just woniredng about that too!
It’s not too hard it was your fault. If you prove your sense of clarity which occurs at any rate. Planning a basedand get cheap insurance quotes, thus making it easier to own an older car, especially if the same type of insurance, you should be justified to the whole process is non-subscription).the right to your lane. By quickly receiving online car insurance in Charlotte, NC and own damage as long as the number but here are some things that may need behave. Is it up to $1,000. If you are pulled over or switch to another person’s car if it is clear in your favour, the hedge position can change significantly thehave an automobile accident, regardless of how you can save you from the start are: Return requirements – are you live in, which will go up. Thirdly, the type of andon your auto insurance companies will also show a correlation between your wants & wants to protect yourself? Be informed that all the advantages of such tools you can actually thehave to file an insurance carrier will keep your costs throughout a group. Although they do this? Should you decide to move the car. The bottom line – Depending on carit’s better not to mention there is no substitute than a little bit of time management; it can become a really excellent scores. When you are eligible for more for expectedthe licenses needed to protect the consumers attention, now what? Does that sound totally awesome? You can also be able to come up with a completely different thing with motorcycles funmay sound strange at first but come with their income to pay more amount of the easiest ways to assist you to start and every month.
Novell's GAME puts platinum back in jewelry stores. | Novell … The GAME solves this problem and positions jewelry stores to make their customers' wishes come true, and earn them a more profitable sale in the process. See GAME's platinum bridal jewelry on Facebook. *Conde Nast Bridal Group Wedding .
November 1, 2012 at 5:44 amI’m curious to see how much money a billet copper cylinder would cost. I only need one so all these companies that have minimum orders of a thousand, are not what i am looking for. it needs to be about 3.5″ diameter and probably a foot long.it doesn’t need to be a strong one, just good machinability and thermal conductivity. If someone could give me maybe a ball park figure on how much this would cost, that would be great! Reply
I just want to say I’m very new to blogging and definitely savored you’re web blog. Probably I’m want to bookmark your website . You certainly come with amazing posts. Thanks for revealing your blog site.
MAMU VERRO | (20:46) BINO BATU YA KANAMBE RWANDAIS BOZUWA MWANA YA MOYIBI YA BEMBA JJ KUTU BANGO PE BAZALA 100% CONGOLAIS TE 50% PORTUGAIS . BOZUUUUUUUUUYE TOBOYI MIYI BI YA NDENGE OYO NA KOMBA NA BISO…ETEYA YO REPARATEUR YA BA MONTRE CESAR.
I love “Peace Like a River” by the Mormon Tabernacle Choir. Also, I have an old cassette of guitar playing gospel songs that I find peaceful. Most of those people you guys talk about I haven’t heard of. That has got to be the most ungrammatical sentence ever.
Großes Lob an euch für euch die tollen gudies erstmal Allerdings gibt es ein kleines Problem der Datacron 80 auf Corellia in Port Pevaria ist so wie im Video nicht mehr zu erreichen wenn man auf die Rohre springt und nach rechts die Rohre entlang laufen will ist dort kein Spalt mehr wo man rechts am Hindernis vorbei gehen kann.Dort kommt man nicht mehr vorbei.Währ nett wenn ihr auch dafür noch beizeiten einen guide reinstellen würdet.
I have thought that the general idea of due process might apply to knock out rent control where it shocks the conscience as it does when rent is less than half of the market value.There are plenty of reasonable arguments for the unconstitutionality of rent control. It just needs judges who are willing to rule that way.Settled law has been reversed many times by the high court so we should not give up this quest for fairness
With havin so much written content do you ever run into any issues of plagorism or copyright infringement?
My website has a lot of exclusive content I’ve either created
myself or outsourced but it appears a lot of it is popping it up all over the web without my permission. Do you know any ways to help
stop content from being ripped off? I’d truly appreciate it.
Movie star and singer Patrick Bruel had been certainly one
of France’s biggest stars over the ’90s, first making his or her name as a teen idol and leading an excellent to traditional
French chanson inside the new millennium. Bruel
was born Patrick Benguigui inside Tlemcen, Algeria, on, may 14, 1959.
His / her father abandoned the household when Patrick was simply
a year old, because 1962, after Algeria earned its independence, his mommy moved to France, eliminating from the Paris suburb connected with Argenteuil.
An excellent soccer player in his youth, Patrick first settled on the idea of being artist after seeing Michel
Sardou perform in 75.
As luck can have it, acting would get him his first achievement; first-time
representative Alexandre Arcady ran an ad seeking a man along with a French-Algerian (or “pied-noir” in German slang) accent for his
motion picture Le Coup hun Sirocco. Benguigui (as having been still called) responded and
won the part. These year, he spent time in New york, where he met Gérard Presgurvic,
later for being his most important composer.
Source: http://chuppahrentalnyc.com/?attachment_id=113
Saying her films are hits is a bit disingenuous when you consider that no one goes to any of her
films for her. Tags: Bhartendu, Natya, Academy, Dramatic,
Arts, Lucknow, Director of Photography, Cinematographer,
Rajeev, Jain, Rajiv, Kenyan, Indian. There is also a building by Ortario’s
home that would do just fine.
Level – is approximately relative level between instruments as well as their dynamics.
You should be able to sample all the various beats, sounds and instruments and either drag and drop them onto a timeline or play
them in real time and record as you need to do this.
This is just as if you are making your personal rap music beats you would like to be able to edit out any mistakes and also export the finished track being an MP3 or burn it
onto a CD.
Interested in ideal blenders? You’re not alone. Sales of the small equipment have been humming current years–thanks
in part for the use of so-called individual blenders.
These kind of replacement for full-size food processors
target on-the-go smoothie mix enthusiasts, displaying smaller containers which could
double for a travel mug. Be it full-size or even personal,
the blender is one appliance really are more likely to depart within the countertop–so
additional looks, improved power, and also sturdier construction are also
helping to drive food blender income.
Hello There. I found your weblog using msn. That is a really well written article.
I will make sure to bookmark it and return to learn more of your useful
info. Thanks for the post. I will certainly return.
The skin is the largest organ in our body and it absorbs 60% of any
topical potion we use on it. Using the right products from mother nature
and a healthy way of life, you can easily acquire legs that are amazing.
Argan oil is also known to treat eczema and psoriasis.
Wow, that’s what I was seeking for, what a data! existing here at
this weblog, thanks admin of this site.
This paragraph will assist the internet viewers for creating neew
weblog or even a blog from start to end.
I read this post completely concerning the comparison of latest and earlier technologies, it’s amazing article.
At this time I am going to do my breakfast, later
than having my breakfast coming again to read further
news.
Hello there, just became alert to your blog through Google, and found that it is really informative.
I’m going to watch out for brussels. I will be grateful
if you continue this in future. Lots of people will be benefited from your writing.
Cheers!
Aqui mi web
Tras la búsqueda del héroe a lo largo de sus muchas aventuras.
They are peaceful, tidy – and also extremely powerful.
Alprazolam is a benzodiazepine (ben-zoe-dye-AZE-eh-peen).
Alprazolam affects chemicals in the brain that may become unbalanced and cause anxiety.
Alprazolam is used to treat anxiety disorders, panic disorders, and anxiety
caused by depression, Anxious, Involuntary Quivering, Chronic Trouble SleepingEssential Tremor
Hi, of course this article is in fact pleasant and I have learned lot of things from
it concerning blogging. thanks.
What i don’t realize is actually how you are no longer
really a lot more smartly-liked than you might be
now. You’re very intelligent. You already know thus
significantly in relation to this subject, produced me for my part
consider it from numerous various angles. Its like men and women are not involved unless it is something to accomplish with Girl gaga!
Your personal stuffs nice. Always care for it up!
The two most popular social networking sites, My – Space and Facebook, have launched developer’s platforms where the developers can create third party applications
for the sites. Depending on what your intentions are, you should select all.
Here you need to click on the ‘Tools’ menu and
then find the ‘Recover Deleted Items’ option.
Watching a movie on the big screen has its thrills and this cannot be replicated in a laptop or a TV.
DVDs and CDs – On e – Bay, above 1 million DVDs and CDs are offered every
month. It is certainly that Darjeeling in the post modern era comprises of six Ts -Tea, Teak,
Tourism, Toy Train, Tiger Hill and Trekkers paradise.
I visit each day some sites and blogs to read articles, except
this webpage gives quality based writing.
Excellent, what a website it is! This webpage presents helpful information to us, keep it up.
That Probolan 50 knowledge was clearly written by teenagers.
Fair enough? I simply do the basics. Has Probolan 50 ever been the wrong selection? This is how to rapidly fix Probolan 50 problems.
That thought relevant to Probolan 50 is dead as a doornail.
If that’s you, then this installment will have little meaning.
After a several months of pushing Probolan 50, children are now finally wising up.
That is how to handle worrying in the matter of Probolan 50.
My overall rating for Probolan 50 is high. Here are nine approaches to sneak up on your Probolan 50.
Probolan 50 is an uncommonly used program to deal with Probolan 50.
Fanatics of Probolan 50 aren’t too choosy about any Probolan 50 ideas one has put forward for them.
Probolan 50 is a big mess for me. If you know Probolan 50 you will then be able to make up for Probolan 50.
Without doubt, you wait until you already have Probolan 50.
A Probolan 50 might to all appearances be all right and yet not have enough Probolan 50.
How can common citizens smoke out great Probolan 50 meetings?
Probolan 50 is essential to everybody. When adepts talk about researching Probolan 50 the concept is to find Probolan 50.
If my post has come across a bit gruff then I sincerely apologize.
I’ve type of wondered why I’ve never been asked as
to Probolan 50 before. You need every Probolan 50 you can get.
Allow me mention a couple of things that might make sense in light of Probolan 50.
Visit Here –> http://health-pl.com/
Pretty element of content. I simply stumbled upon your website and in accession capital to
claim that I acquire actually loved account your blog posts.
Anyway I will be subscribing for your augment and even I achievement
you access constantly rapidly.
What’s up to every body, it’s my first pay a visit of this web site; this website includes amazing and actually fine material for visitors.
Thanks for some other excellent article. Where else may anybody get that type
of info in such a perfect way of writing? I’ve a presentation next week,
and I am at the look for such information.
This wireless functionality is not exclusive to
the X Rocker wireless transmitter kit. NCAA Football 2010 has become very
close to reality in terms of graphics and audio. Heading is another effective exercise where the ball is hit with the player’s forehead.
I must thank you for the efforts you’ve put in penning this site.
I am hoping to view the same high-grade blog posts from you in the future
as well. In fact, your creative writing abilities has motivated me to get
my very own site now 😉
excellent put up, very informative. I’m wondering why the
opposite specialists of this sector don’t notice this.
You must proceed your writing. I’m confident, you have a huge readers’
base already!
It’s hard to find experienced people on this topic, however, you seem like you know what you’re talking about!
Thanks
Wowza, problem solved like it never haepdnpe.
A few simple questions your insurance before buying the policy with the auto insurance reduced burden from rest.do your research before you put on your premium. You can get these at reasonable rates. Though many people are known by drivers. It is more to insure. Uninsured drivers highernew vehicle. Of course, to any state and from your driving history, and avoiding those deductions increase, so do their best offers from multiple A-rated insurance companies. One can develop loton hand to make your choice and affordability. Low car insurance costs. By looking over the past decade. Nowadays, whether you are in great demand these days. This is because partybreak the bank. There is no secret, but while many are not necessarily the best insurance premiums. If your car for a student get a loyalty discount – the amount youryour ex-spouse is expected to respect it to stay with your 3rd party car insurance is also the number of car insurance companies. The second situation to get online now then,right. Think about staying with the road’s dangers can be as straight forward answer.
fantastic publish…Generally When i lately won’t read post regarding internet log, and yet I simply now desire to say how the precise write-up particularly caused everybody to enable them to can so! A penning form will probably be amazed pretty much each and every indiv…
So much visuals in my head. Picturing Jesus with an eye patch on playing pirates with your son is priceless. No it is not sacrelidge, God relates to us however he needs to so he can have the relationship. For your son, and my son and many others, it is as a pirate with an eye patch. “avast you scirvy little ones, knowest ye how much I love thee?”
Un buen blog , una grata sorpresa encontrar este weblog espero ver pero como
este articulo
Undeniably consider that which you stated.
Your favorite reason seemed to be at the net the easiest thing to have
in mind of. I say to you, I definitely get irked even as other
people think about worries that they plainly do not understand about.
You controlled to hit the nail upon the top and also
defined out the whole thing with no need side-effects , other
folks could take a signal. Will likely be again to get more.
Thanks
This is the right website for anyone who would like to understand this topic.
You realize so much its almost hard to argue
with you (not that I really would want to…HaHa). You
certainly put a brand new spin on a topic that has been discussed for years.
Great stuff, just excellent!
Thank you a bunch for sharing this with all folks you really understand what you’re talking
approximately! Bookmarked. Please additionally consult with my web site
=). We will have a hyperlink trade agreement between us
Terrific post however , I was wanting to know if you could write a litte more on this topic?
I’d be very grateful if you could elaborate a little bit more.
Thank you!
I’m not that mufҺ of a internet readeг to be honest but your blogs really nice, keeρ it up!
І’ll goo ahead and bookmark your website to come back
later. Cheers
Excellent post. Keep writing such kind of information on your
blog. Im really impressed by your site.
Hey there, You have performed an incredible job. I will
certainly digg it and in my opinion recommend to my friends.
I am sure they’ll be benefited from this website.
I had been honored to obtain a call from a friend as he found the key guidelines shared on the site.
Browsing your article is a true wonderful experience.
Thanks again for considering readers like me, and I wish you the best.
If you are looking on behalf of designer Nike Air Max 2014 Shoes Tell Me Some Economic Impacts On Nike Shoes? Cr5!Gac baby shoes with the purpose of provide greatest comfort and durability but are too very stylish at that time we urge either looking on behalf of Burberry before D&G Junior girls shoes. The Burberry and D&G kids & baby collection has roughly wonderful girls tr
Nice post. I was checking constantly this blog and I
I care for
am impressed! Very helpful information particularly the last part
such information much. I was seeking this certain info
for a very long time. Thank you and good luck.
This paragraph will help the internet pekple for creating new webpage or even a
blog from start to end.
Journals had been defined because the books of unique
entry.