From 491f496a7143e70ba58cbf25d700267ac96783fa Mon Sep 17 00:00:00 2001 From: José Mota Date: Mon, 22 Oct 2012 12:42:39 +0100 Subject: Convert Rails 3 associations post to Markdown. --- ...-09-same-class-associations-in-rails-3.markdown | 43 ++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 _posts/2011-12-09-same-class-associations-in-rails-3.markdown (limited to '_posts/2011-12-09-same-class-associations-in-rails-3.markdown') diff --git a/_posts/2011-12-09-same-class-associations-in-rails-3.markdown b/_posts/2011-12-09-same-class-associations-in-rails-3.markdown new file mode 100644 index 0000000..e7062e4 --- /dev/null +++ b/_posts/2011-12-09-same-class-associations-in-rails-3.markdown @@ -0,0 +1,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 Students that have a Record +per year. Each record has several Events. These records also have two +specific events: a test and an audition, 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 r = Record.first, when I tried to +access the audition, by using r.test, Rails would use a SQL query +that would correspond to r.events.first instead. + +After acknowledging that, I turned to @varandas 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 has\_one to belongs\_to (thanks @drogus!). The reason for that is the + foreign key is on the records table. From the framework's + perspective, it looks like the record actually belongs to the event, + when in practice it's not. + +### Code sample + + -- cgit v1.2.3-54-g00ecf