Ruby on rails 模型方法与轨道的相互作用
在我的“课程”模型中: 一种方法是选择属于某个课程的所有用户IDRuby on rails 模型方法与轨道的相互作用,ruby-on-rails,ruby-on-rails-4,model,Ruby On Rails,Ruby On Rails 4,Model,在我的“课程”模型中: 一种方法是选择属于某个课程的所有用户ID def participants Course.joins(:click).pluck(:user_id) end 另一种方法是随机选取一个用户id def set_winner Course.participants.sample end 但是,我得到以下错误: undefined method `participants' for #<Class:0x007fc639811468> 未定义的方法“参与
def participants
Course.joins(:click).pluck(:user_id)
end
另一种方法是随机选取一个用户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
课程{joins(:click).pull(:user_id)}
范围:set_winner,->{participants.sample}
结束