SQL

:has_many Associations with Complex Joins (Kind of)

Duck VaderIn this episode, your fearless Jedi delves within the dark tree of associations, with_scope, inner joins, duck typing and meta-programming all in an effort to keep DRY…

In Joyomi I create an Omi when I lend you a book. I can optionally share that Omi with you. If I do, then the Omi shows up in the “Omis Shared With Me” tab in your dashboard. Sharing. Mkay. Social networking 101.

Now the query for a Joyomi user to find his own Omi’s (one’s he’s created) is trivial. The user model simply has_many omis. No brainer. On the other hand, going in the opposite direction and finding all the Omi’s that my friends have shared with me is decidedly non-trivial. In fact it’s downright tricky. It involves a big long series of joins. This is further complicated by the fact that in order to address potential SPAMming we don’t show you Omi’s that were created by folks who are not in your contact list. Got that? Good.

Continue Reading »

Ruby on Rails
SQL

Comments (1)

Permalink

Put NULLS Last on MySQL

NULLs are a wonderful but strange feature of SQL. They are the source of some deep coolness but also some lost hair. One place where NULLs can bite you is when you are sorting. The way you sort in SQL is by appending the ORDER BY clause to the end of a SELECT statement. The problem is that the SQL standards say that for the purpose of sorting, NULL = NULL but they don’t specify how NULL values should be ordered relative to non-NULL ones. Doh!

In this post I describe the solution to this problem in the context of MySQL and Ruby on Rails.
Continue Reading »

Ruby on Rails
SQL

Comments (6)

Permalink