sparkle
sparkle

Reputation: 7398

How to add a method for active record?

I would want to use my method getScheduleFixed() on a Active Record Istance

ps = ProgramSchedule.all
ps.getScheduleFixed

the important fact is how to access to "ps" array (active record) on my method declaration

class ProgramSchedule < ActiveRecord::Base

  def getScheduleFixed

    array = (HERE ARRAY RETURNED BY ACTIVE RECORD)

    # some stuff...

    return array

  end
end

Upvotes: 0

Views: 105

Answers (4)

ShadyKiller
ShadyKiller

Reputation: 710

I think you should use scope for this:

class ProgramSchedule < ActiveRecord::Base

  scope :fixed, { all.map(&:getScheduleFixed) }

end

or

class ProgramSchedule < ActiveRecord::Base

  def self.fixed
    all.map(&:getScheduleFixed)
  end

end

Now you just need to call ProgramSchedule.fixed. Both these methods can be chained on other scopes such as ProgramSchedule.latest.fixed. See more details here

Upvotes: 1

Thomas Klemm
Thomas Klemm

Reputation: 10856

You are mixing things up here.

1) There are (instance) methods that you can use on a single ActiveRecord object.

# Returns an ARRAY with all programschedule instances
all_ps = ProgramSchedule.all

# You can now iterate over over the array
all_ps.each do |ps|
  # in here you can call the instance method on the actual model instance
  ps.instance_method
end

# Definition of this method in app/models/program_schedule.rb
class ProgramSchedule < ActiveRecord::Base
  def instance_method
    # Foo
  end
end

2) There are class methods that you can run on the ActiveRecord model itself.

ProgramSchedule.class_method

# Definition of this method in app/models/program_schedule.rb
class ProgramSchedule < ActiveRecord::Base
  def self.class_method
    # Bar
  end
end

Upvotes: 1

tomferon
tomferon

Reputation: 5001

When you do ProgramSchedule.all, you get an Array, not an instance of ProgramSchedule.

If your method will be called with all the records at all times, you can use a class method like this one :

class ProgramSchedule < ActiveRecord::Base
  def self.getAllScheduleFixed
    array = ProgramSchedule.all # or self.class.all could be used if you subclass this class
    #some stuff
  end
end

If you need to work with only a subset of ProgramSchedule's, that is conditions, you will need to pass conditions to this class method, or to directly pass the array of results to some class method.

Upvotes: 1

Salil
Salil

Reputation: 47532

  def getScheduleFixed
    array = User.all.map(&:name)
    return array
  end

Upvotes: 0

Related Questions