[英]Interaction of model methods rails
在我的“课程”模型中:
一种方法应该选择属于某个课程的所有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>
如果有人可以向我解释,为什么这行不通,我将非常感激。
您的示例无效,因为您定义了实例方法。 然后尝试将它们作为类方法在类上运行。要解决该问题,可以编写:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.