Linoor is a premium Template for Digital Agencies, Start Ups, Small Business and a wide range of other agencies.
888 999 0000


You are here:
Estimated reading time: 1 min

The thing is; we now want to associate those two models. We want to be able to keep track of which pins belong to which user. Luckily Rails makes this pretty easy with something called “Associations”. In Rails, there are a few basic types of associations available to you: – belongs_to
– has_one
– has_many
– has_many :through
– has_one :through
– has_and_belongs_to_many
Each of these associations can refer to a model in our app (in our case, let’s look at our pins model). We mainly want to focus on the first three: A pin can “belong to” a user. A user can “have one” pin. A user can “have many” pins. The other three listed above are for more complicated associations that we don’t really need to understand for our simple app. But you can read a great rails guide about each of these associations at:



$ rails generate migration add_user_id_to_pins user_id:integer:index

$ rake db:migrate


The next thing to do is actually specify our associations. We do that in our two /app/models/ files (pin.rb and user.rb). /app/models/pin.rb
1 class Pin < ActiveRecord::Base
2 belongs_to :user
3 end

1 class User < ActiveRecord::Base
2 # Include default devise modules. Others available are:
3 # :confirmable, :lockable, :timeoutable and :omniauthable
4 devise :database_authenticatable, :registerable,
5 :recoverable, :rememberable, :trackable, :validatable
6 has_many :pins
7 end


You see that adding associations is as simple as adding one line to each model. Piece of cake!


Finally, we mentioned at the beginning of this chapter that we only want people who are signed in to be able to create pins.

This is easily accomplished by tweaking our pins controller file, and adding a couple of lines to the top of it:


Was this article helpful?
Dislike 0
Views: 9