Ruby on rails Rails:为需要自己类成员信息的类创建方法?

Ruby on rails Rails:为需要自己类成员信息的类创建方法?,ruby-on-rails,class,ruby-on-rails-3,methods,model,Ruby On Rails,Class,Ruby On Rails 3,Methods,Model,我想知道是否有可能做到以下几点: 假设我有一个Rails模型,Foo,带有一个数据库属性valueFoo属于Bar,Bar有很多Foo 在我的模型中,我想做如下事情: class Foo < ActiveRecord::Base belongs_to :bar def self.average # return the value of all foos here end end 这样的事情可以做吗?如果可以,怎么做?谢谢 只要您确保调用self上的方法,而不是

我想知道是否有可能做到以下几点:

假设我有一个Rails模型,
Foo
,带有一个数据库属性
value
Foo
属于
Bar
Bar
有很多
Foo

在我的模型中,我想做如下事情:

class Foo < ActiveRecord::Base

  belongs_to :bar

  def self.average
    # return the value of all foos here
  end

end

这样的事情可以做吗?如果可以,怎么做?谢谢

只要您确保调用
self
上的方法,而不是
average
方法主体中的
Foo
,您所拥有的将按原样工作。在
Foo
的作用域上调用方法时,该方法主体中的
self
将分配给作用域对象,而不是
Foo
。这里有一个更具体的例子:

# app/models/club.rb
class Club < ActiveRecord::Base
  # name:string
  has_many :people
end

# app/models/person.rb
class Person < ActiveRecord::Base
  # club_id:integer, name:string, age:integer
  belongs_to :club

  def self.average_age
    # note that sum and count are being called on self, not Person
    sum('age') / count
  end
end

只要确保调用
average
方法主体中的
self
而不是
Foo
上的方法,您所拥有的将按原样工作。在
Foo
的作用域上调用方法时,该方法主体中的
self
将分配给作用域对象,而不是
Foo
。这里有一个更具体的例子:

# app/models/club.rb
class Club < ActiveRecord::Base
  # name:string
  has_many :people
end

# app/models/person.rb
class Person < ActiveRecord::Base
  # club_id:integer, name:string, age:integer
  belongs_to :club

  def self.average_age
    # note that sum and count are being called on self, not Person
    sum('age') / count
  end
end

啊哈!我不知道“count”,我想我需要做一些像self.each do{#stuff}这样的事情,这显然不起作用。谢谢,这很有帮助!啊哈!我不知道“count”,我想我需要做一些像self.each do{#stuff}这样的事情,这显然不起作用。谢谢,这很有帮助!
$ rails console
Loading development environment (Rails 3.0.3)
irb(main):001:0> boys_club = Club.create(:name => 'boys')
irb(main):002:0> girls_club = Club.create(:name => 'girls')
irb(main):003:0> boys_club.people.create(:name => 'bob', :age => 20)
irb(main):004:0> boys_club.people.create(:name => 'joe', :age => 22)
irb(main):005:0> girls_club.people.create(:name => 'betty', :age => 30)
irb(main):006:0> Person.average_age
=> 24
irb(main):007:0> boys_club.people.average_age
=> 21
irb(main):008:0> Person.where("name LIKE 'b%'").average_age
=> 25