Juri Bojka Juri Bojka - 3 months ago 13
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.

User.rb:

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
end


And Article model:

class Item < ActiveRecord::Base
has_many :follow_articles
end


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

@articles = current_user.follow_articles


which gave me:

ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_FollowArticle:x3014X2


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?

Answer

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
  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