【问题标题】:Call a method on a Class object在 Class 对象上调用方法
【发布时间】:2015-11-29 20:08:08
【问题描述】:

我的任务是向Profile 类添加一个类方法,称为get_all_profiles,其中:

  • 接受出生年份的最小值和最大值

  • WHERE 子句中发出BETWEEN SQL 子句来定位出生年份介于最小年份和最大年份之间的Profiles

  • 在将参数应用于 SQL 子句

  • 按 ASC 出生年份顺序返回 Profile 集合

我认为下面的实现是正确的,但是如何在类对象(即Profile.get_all_profiles?(min, max))上调用它?

def get_all_profiles(start_year, end_year)
  Profile.where(:birth_year => start_year..end_year).order(:birth_year )
end

【问题讨论】:

  • 前段时间也有同样的问题
  • 你错过了一个关键部分,他们说添加一个 class 方法。您必须将其定义为def self.get_all_profiles(start_year, end_year),然后您可以将其称为Profile.get_all_profiles(...)。请务必阅读有关实例方法和类方法之间区别的讲义。

标签: ruby-on-rails ruby record


【解决方案1】:

要将其实现为类方法,您可以将上述方法编写为:

def self.get_all_profiles(start_year, end_year)
  Profile.where(:birth_year => start_year..end_year).order(:birth_year )
end

或者,

class << self

  def get_all_profiles(start_year, end_year)
    Profile.where(:birth_year => start_year..end_year).order(:birth_year )
  end

  ... other class methods ...

end

所以你可以这样称呼它:

Profile.get_all_profiles(start_year, end_year)

【讨论】:

  • 感谢所有回复 def self.get_all_profiles(start_year, end_year) where(birth_year: start_year..end_year).order(:birth_year) end 为我工作
猜你喜欢
  • 2011-06-19
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
相关资源
最近更新 更多