summaryrefslogtreecommitdiff
path: root/_posts/2011-12-09-same-class-associations-in-rails-3.markdown
blob: e7062e41fb31c7cfef24c86ab06d3220529284bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
---
layout: post
title: Same class associations in Rails 3
tags: development
type: post
published: true
---

**[TL;DR]** Even though the selected events conceptually belong to a record,
the latter has the foreign keys to former. So technically, `has_one`
is to be changed to `belongs_to`.

* * *

This is the first time I've ran into something like this and it was interesting
to realize what it actually means when developing a business logic in Rails.

### Context

In this app I'm building, I have <em>Students</em> that have a <em>Record</em>
per year. Each record has several <em>Events</em>. These records also have two
specific events: a <em>test</em> and an <em>audition</em>, registered in the
schema as `id`'s in the record's table.

### So what did technically happen?

I wasn't able to access those specific events through the associations
specified in the model. Given <code>r = Record.first</code>, when I tried to
access the audition, by using <code>r.test</code>, Rails would use a SQL query
that would correspond to <code>r.events.first</code> instead.

After acknowledging that, I turned to <a
href="http://twitter.com/varandas">@varandas</a> and we both thought it might
be a bug in the Rails framework. Turns out it wasn't; all I had to do was
switch from <code>has\_one</code> to <code>belongs\_to</code> (thanks <a
  href="http://github.com/drogus">@drogus</a>!). The reason for that is the
  foreign key is on the <code>records</code> table. From the framework's
  perspective, it looks like the record actually <em>belongs to</em> the event,
  when in practice it's not.

### Code sample

<script src="http://gist.github.com/1449428.js"></script>