In Rails we can establish many to many relationship between two models in two ways 1) by using has_and_belongs_to_many 2) by using has_many :through associations.
We generally use HABTM when we dont require a third intervening model to join two other models i.e the third table in the database will have just the foreign keys of the other two tables. The third model will have no extra attributes or any validation and callbacks.
class User < ActiveRecord::Base
class Role < ActiveRecord::Base
Here we have to create a third joining table users_roles.
In case of has_many :through relation we can have many to many relation in indirect way through a third joining model.
Example: Below are the three models of an online shopping website:
class User< ActiveRecord::Base
has_many :items, through: :user_items
class UserItem< ActiveRecord::Base
class Item < ActiveRecord::Base
has_many :users, through: :user_items
Here the user_items table will have the foreign keys of the two table and some additional information like date_of_delivery, payment_method(cash or card) e.t.c.