0

I'm using the Ruby Gem 'Socialization', to do some follow/like stuff, on my models.

Scenario: User can follow a subject, and by the subject, the user can the retrieve all the articles under a given subject. So, i couldn't really figure out, how to do this with the methods provided by the gem. So i tried making my own methods, in the user model.

class User < ActiveRecord::Base
  ..

  acts_as_follower
  acts_as_liker

  def get_subjects
    follows = self.follows

    f = []

    follows.each do |follow|
      f << follow.followable
    end

    return f
  end

  def get_articles
    subjects = self.get_subjects

    a = []

    subjects.each do |subject|
      if subject.articles.count > 0
        a << subject.articles
      end
    end

    return a
  end

..
end

What I'm trying to do here, is find the articles, that the user would be interested in, based on the subjects the user follows.

This may work okay, however I'm sure it can be done much better. Is there anyone who can guide me a bit here?

Thanks, Oluf.

Oluf Nielsen
  • 769
  • 1
  • 8
  • 24

1 Answers1

1

Maybe this simple solution would be appropriate?

In the subject's model:

has_many :articles

In the user's model:

has_many :subjects
has_many :articles, through: :subjects

After that, the user has a method articles:

@user.articles
Marcel Hebing
  • 3,072
  • 1
  • 19
  • 22
  • Hey Fernando! Thanks for the approach, but the follow process is a polymorphic relation.. But the subjects/article relation is a has_many/belongs_to! :-) – Oluf Nielsen Jan 27 '13 at 21:45
  • The `has_many ..., through ...` method works also for polymorphic associations and has_and_belongs_to_many relations. See: http://stackoverflow.com/questions/1683265/activerecord-has-many-through-and-polymorphic-associations – Marcel Hebing Jan 27 '13 at 21:48