简体   繁体   中英

How do you define a class method?

I have a model OutcomeData with controller OutcomeDatas.

In OutcomeData, I have a method as_cleaned_hash that right now, doesn't do a damn thing. Let's just pretend it returns 'hello'

class OutcomeData < ActiveRecord::Base
  attr_accessible :key, :outcome_uid, :task_id, :value

  belongs_to :task
  belongs_to :outcome

  def as_cleaned_hash
    'hello i am alive'
  end

This is the method that as_cleaned_hash is supposed to follow, if it matters:

@outcome_data = OutcomeData.find_all_by_outcome_uid(params[:outcome_uid])
hash = Hash.new
@outcome_data.each do |p|
  unless p[:value].blank? || p[:key] == 'raw'
    hash[p[:key]] = p[:value]
  end
end

This works fine -- right now I'm throwing it into my controller actions, but since it needs to be used throughout my app, I can't let this happen.

So, for whatever reason, I get an undefined method error.

I called OutcomeData.methods to see if the method was even there, and, nope. (see list here: http://pastebin.com/B3y1r2w7 )

OutcomeData.respond_to?('as_cleaned_hash') returns false.

There's nothing fancy going on either, so I'm not quite sure what's happening.

Rails 3.2.12 with Ruby 2.0.0-p195

To define a class method, the syntax is

def self.foo
end

You have defined an instance method.

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