[英]Interaction of model methods rails
Inside my "Course" model: 在我的“课程”模型中:
One method is supposed to select all user_ids which belong to a certain course 一种方法应该选择属于某个课程的所有user_id
def participants
Course.joins(:click).pluck(:user_id)
end
The other method is supposed to pick a random user_id 另一种方法应该选择一个随机的user_id
def set_winner
Course.participants.sample
end
However, I get the following error: 但是,出现以下错误:
undefined method `participants' for #<Class:0x007fc639811468>
If somebody could explain to me, why this doesn't work, I'd be really grateful. 如果有人可以向我解释,为什么这行不通,我将非常感激。
Your example doesn't work because you define instance methods. 您的示例无效,因为您定义了实例方法。 And then you try to run them on class as if they are class methods.To fix it you could write:
然后尝试将它们作为类方法在类上运行。要解决该问题,可以编写:
def self.participants
Course.joins(:click).pluck(:user_id)
end
def self.set_winner
Course.participants.sample
end
or, better 或更好
class Course < ActiveRecord::Base
scope :participants, -> { joins(:click).pluck(:user_id) }
scope :set_winner, -> { participants.sample }
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.