模型方法轨道的交互

时间:2014-10-04 18:45:55

标签: ruby-on-rails ruby-on-rails-4 model

在我的“课程”模型中:

一种方法应该选择属于特定课程的所有user_id

def participants
  Course.joins(:click).pluck(:user_id)
end

另一种方法应该是随机选择user_id

def set_winner
  Course.participants.sample
end

但是,我收到以下错误:

undefined method `participants' for #<Class:0x007fc639811468>

如果有人能向我解释,为什么这不起作用,我会非常感激。

1 个答案:

答案 0 :(得分:1)

您的示例不起作用,因为您定义了实例方法。然后你尝试在类上运行它们,就像它们是类方法一样。要修复它,你可以写:

def self.participants
  Course.joins(:click).pluck(:user_id)
end

def self.set_winner
  Course.participants.sample
end

或更好

class Course < ActiveRecord::Base
  scope :participants, -> { joins(:click).pluck(:user_id) }
  scope :set_winner, -> { participants.sample }
end