As promised last week, today is dedicated to delicious Rails! This post is the first of several in which I'll talk about how the various feature implementations in Sutro, the blog engine that runs this site. In particular, today will focus on what it means to add tags to articles, and how to associate the models underneath.
Models and Associations
Rails associations are a set of methods that enable us to tie conceptually related models together and describe their relationships. For example, a Car belongs to a Person, and a Customer has many Orders. The association keywords "belongs to" and "has many" are several of the built in associations that Rails provides. We'll see that by specifying the relationships between two models (posts and tags here), we gain access to high-level helper methods that make our lives infinitely easier.
Our first step is the most important - determing the right relationship to use between posts and tags. The complete list of Rails model associations, as well as an explanation of their purpose and usage can be found at the RailsGuide here. So which ones are right for our needs? Well, clearly a post can have many tags. But remember, the relationship must be defined both ways. In that case, a
post has_many :tags and a
tag belongs_to :post relationship seems like the obvious choice. After some thought though, you'll realize that's not right. A post can have many tags, but a tag can also belong to many posts. For example, if a post is tagged with "ruby", the "ruby" tag is not locked to that post. Many posts can be tagged with the same name. So the association we're looking for is
has_and_belongs_to_many. A post has and belongs to many tags, and a tag has and belongs to many posts. This is a mouthful, and gets a bit complicated to put in place, but ultimately, it allows us to call the methods
@tag.posts, which will be enormously useful. Let's move on to generating our models and migrations!