简体   繁体   中英

Interaction of model methods rails

Inside my "Course" model:

One method is supposed to select all user_ids which belong to a certain course

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

The other method is supposed to pick a random 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM