简体   繁体   English

Ruby on Rails,使用类方法?

[英]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? 我是Ruby on Rails的新手,我想知道拥有很多类变量是否很好?

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. 我不明白为什么我们为此需要接口,如果您正在寻找一种在类外编写方法并加以利用的方法,那么您可能会研究模块和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 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/ http://zachholman.com/2010/01/simplifying-rails-controllers-with-named_scopes/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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