How to add a method to an activerecord collection?

前端 未结 3 1472
时光取名叫无心
时光取名叫无心 2021-02-18 23:37

I would like to add a method to all collections for a specific model. Let\'s say I want to add the method my_complicated_averaging_method to the WeatherData collect

3条回答
  •  没有蜡笔的小新
    2021-02-19 00:19

    It looks good to get things working, but for more finesse I'm sure there is something much better. Admittedly, you weren't too specific in describing what you wanted to achieve with this, so I can only give you this broad suggestion

    You may want to look into "Observer Classes"


    I wrote a post about them here

    Observer Classes basically monitor a particular model function & extend it. I think they're only for the before_filter, etc functions, but I don't see why you can't extend indvidual functions that you create

    You'll have to use the rails-observers gem in rails 4.0+ to get them working, as they've been depreciated from the rails core

提交回复
热议问题