简体   繁体   中英

Ruby on Rails, Using Class Methods?

I'm a newbie to Ruby on Rails, and I'm wondering is it good to have a lot of class variables?

I'm currently working on a project, an enrollment website. I have a class Student with quite a few attributes. Currently, I only have mostly instance methods that return a specific student's attributes. I also have a generic search function to search for a student using his student ID.

My problem is that I want it to be able to get aggregate information about the students, like what program has most students, how many students are in the 6th grade, etc.

In order to do this, I was thinking of just adding some class methods to filter the students. Is there a better way to do this? Like creating an interface?

Thanks a lot in advance! Any help would be very much appreciated. :)

I didn't understand why we need interface for this purpose, if your are looking for a way to write a method outside the class and make use of it, you may look into modules and mixins.

If I understand correctly, your requirement can be fulfilled with the use of scope,

User model:

scope :sixth_grade, where("grade='6'")
scope :programs, select("program, count(*) as program_count").group("program")

You should checkout named scopes for what you want to do. Checkout the following articles on how you can use scope to do what you are thinking of doing using class methods:

  1. http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html

  2. http://zachholman.com/2010/01/simplifying-rails-controllers-with-named_scopes/

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