How do you model an article that has an author and readers w/ the same User model?

Hi,

I am stuck trying to figure out how to model this.

I have a user model and an article model.

It is easy enough to say the user has many articles and the article
has one user.

class User < ActiveRecord::Base
has_many :articles
end

class Article < ActiveRecord::Base
belongs_to :user
end

But how do I add the concept of an article having many readers? The
readers would be using the same User model since a User can author
many articles but can also be reading many other articles.

Your help would be most appreciated.

Thanks,
Frank

Well I’m certain this isn’t a working answer, I thought I’d post
anyways in hopes that maybe something I say here will jump start your
brain, and ultimately lead you to the solution. None of this code was
tested.

#This one just uses habtm to make a join table for readers/reads

class User < ActiveRecord::Base
has_many :articles
has_and_belongs_to_many :reads, :class_name => ‘Article’
end

class Article < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :readers, :class_name => ‘User’
end


This one makes the join table explicitly and tries to use some fancy

has_many options.

The :source-'s might be flipped, I’m not sure how those work

exactly. Again this code

isn’t tested, I just read through

and came up with the best thing I could.

class User < ActiveRecord::Base
has_many :articles
has_many :readings, :through => :reads, :source => :user
end

Read as in ‘that was a good read(noun)’, NOT ‘he read(verb) well’.

Helps me to wrap my head around it better.
class Read < ActiveRecord::Base
belongs_to :user
belongs_to :article
end

class Article < ActiveRecord::Base
belongs_to :user
has_many :readers, :through => :reads, :source => :article
end

Again I can’t stress enough that I do not know at all if this will
work, so if your messing with it and you don’t possibly see how it
could work, it probably doesn’t. Move on an find an answer from
someone more experienced (I have less than 6 months exp. in Rails/
Ruby, and use it much more as a hobby, and not a profession).

I’d suggest a join class called ‘Subscription’ that belongs_to :user
and :article. With that you could also add some helpful attributes to
the join (e.g., ‘can_reply’, or ‘last_read_at’). If you add that then

User
has_many :articles
has_many :subscriptions

has_many :articles_to_read, :class_name=>‘Articles’,
:through=>subscriptions
end

Article
belongs_to :user
has_many :subscriptions
has_many :readers, :class_name=>‘User’, :through=>:subscriptions
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs