如何为活动记录添加方法?

时间:2012-10-30 11:15:23

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

我想在Activerecord实例上使用我的方法getScheduleFixed()

ps = ProgramSchedule.all
ps.getScheduleFixed

重要的事实是如何在我的方法声明

上访问“ps”数组(活动记录)
class ProgramSchedule < ActiveRecord::Base

  def getScheduleFixed

    array = (HERE ARRAY RETURNED BY ACTIVE RECORD)

    # some stuff...

    return array

  end
end

4 个答案:

答案 0 :(得分:1)

执行ProgramSchedule.all后,您会获得Array,而不是ProgramSchedule的实例。

如果您的方法将始终使用所有记录调用,您可以使用类似这样的类方法:

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

如果你只需要使用ProgramSchedule的一个子集,那就是条件,你需要将条件传递给这个类方法,或者直接将结果数组传递给某个类方法。

答案 1 :(得分:1)

你在这里搞混合。

1)您可以在单个ActiveRecord对象上使用(实例)方法

# 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)您可以在ActiveRecord模型上运行类方法

ProgramSchedule.class_method

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

答案 2 :(得分:1)

我认为你应该使用范围:

class ProgramSchedule < ActiveRecord::Base

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

end

class ProgramSchedule < ActiveRecord::Base

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

end

现在你只需要致电ProgramSchedule.fixed。这两种方法都可以链接到其他范围,例如ProgramSchedule.latest.fixed。查看更多详情here

答案 3 :(得分:0)

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