When I developed my first sandbox application, I wanted to get some records for relational table.
class User < ActiveRecord::Base
#has many followed articles
class FollowArticle < ActiveRecord::Base
class Item < ActiveRecord::Base
@articles = current_user.follow_articles
<% @articles.each do |article| %>
<%= article.article.name %>
<% end %>
@items = current_user.follow_articles
From the Guide:
A has_many :through association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model. For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:
class Physician < ApplicationRecord has_many :appointments has_many :patients, through: :appointments end class Appointment < ApplicationRecord belongs_to :physician belongs_to :patient end class Patient < ApplicationRecord has_many :appointments has_many :physicians, through: :appointments end
So, fully connecting the dots...
#User.rb class User < ActiveRecord::Base has_many :follow_articles has_many :followed_articles, through: :follow_articles end