It is our last full week coding at Flatiron, and we are working hard on our final projects. The application we are building allows users to both post food items they will not use and allow others to claim those items posted by others. We wanted to make sure individuals using the application could be both Posters and Claimers. In order to accomplish this we had to alter our associations and create new aliases. It was a great review of these concepts and working it out through our new application really helped me understand them and how to use them.
When you create an association, Rails makes two major assumptions
- The class of the model your association points to is based directly off of the name of the association
- The foreign key in a belongs_to relationship will be called yourassociationname_id.
Any time you go away from these defaults, you need to let Rails know what kind of class to look for and which foreign key to use.
Suppose you want to refer to a model as two different things and setup the associations to reflect this. We used this in a Flatiron lab that referred to AirBnB. In this lab a single User could be a Host or a Guest. We wanted to be able to refer to the same individual as both a host and a guest throughout our app and know that this was actually the same user. This is called aliasing - where we are giving one user two names throughout the app.
In our final project we also have a user, however, we wanted to refer to the user as someone who posts food to our site (a poster) as well as someone who could claim food (a claimer). Here we want access to :poster_id and :claimer_id and not just :user_id.
To do this we had to modify our associations in our models. Once we modify these associations we can actually refer to these aliases throughout the app. Rails knows that there will be times when you want to customize the behavior of your belongs_to association reference. These customizations are accomplished by passing options and scope blocks when you create the association. You can use the :class_name option to give a new model name. For example, in our app, if a food item belongs to a Poster, but the actual name of the model containing users of our site is User, you’d set things up this way:
1 2 3 4 |
|
The next step is to set the set the alias foreign key’s directly. The :foreign_key option lets you set the name of the foreign key like this:
1 2 3 4 |
|
The basic concept here is that rails allows you to have aliases by following the convention that applies to all association - the models name have to be referred (we are just using :class_name to refer to the names we made up) and then we have to get the app using the correct forgin key with :foreign_key.