简体   繁体   中英

Organizing Classes and Objects in Ruby?

I am a beginner with Ruby on Rails. I have a question regarding organizing objects and classes.

I have an Article class that has a few fields, like author, keywords, date, etc.

The problem is that I want to organize these article objects to be able to analyze them collectively. The articles come from different sources and I want to be able to access them based on the source.

I am guessing I can have a new class for ArticleSource and relate it to the Article class through relationships such as has_one or embeds_one. Am I doing this right, or is there a better way?

Thanks in advance!

I think you should look into single table inheritance here.

Keep Article as a super class and inherit it into sub classes as ExtertArticle(source is expert) and StudentArticle etc...

Reference: http://api.rubyonrails.org/classes/ActiveRecord/Base.html

I think has_many and belongs_to will do what you want.

After adding an article_source_id column to the Article table, your classes would look something like this:

class ArticleSource
  has_many :articles
end

class Article
  belongs_to :article_source
end

Then you can analyze the articles collectively using code like this:

source = ArticleSource.find_by_name("New York Times");
articles = source.articles

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM