Juri Bojka Juri Bojka - 1 month ago 4x
Ruby Question

How to get relation records over relation table issue

When I developed my first sandbox application, I wanted to get some records for relational table.


class User < ActiveRecord::Base
#has many followed articles
has_many :follow_articles

And FollowArticle model:

class FollowArticle < ActiveRecord::Base
belongs_to :user
belongs_to :article

And Article model:

class Item < ActiveRecord::Base
has_many :follow_articles

I want to get all followed articles of a user so in my controller I have:

@articles = current_user.follow_articles

which gave me:


In my view I can iterate over these articles:

<% @articles.each do |article| %>
<%= article.article.name %>
<% end %>

which works perfectly.

Can I do this in this way to get an Articles array instead of a FollowArticles array, something like:

@items = current_user.follow_articles

to return articles instead of followArticles?


Use has_many :through.

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

  class Appointment < ApplicationRecord
    belongs_to :physician
    belongs_to :patient

  class Patient < ApplicationRecord
    has_many :appointments
    has_many :physicians, through: :appointments

So, fully connecting the dots...

  class User < ActiveRecord::Base
    has_many :follow_articles
    has_many :followed_articles, through: :follow_articles