6

I'm currently using the find or create method to update an associated record which i use to store cached information, but I'm wondering if there's some simpler alternative method similar to build since the object is a has_one relation. The problem with just using build_ is in most cases the object will exist and needs to be updated. I could use a bunch of ifs the check but wondered if there was some better rails-fu than I'm using currently.

  def self.update_caches(data)
    cache = SpaceCache.find_or_create_by_space_id(@space.id)
    cache.rating = ((data.ratings.sum / data.ratings.size)/20).round
    cache.price_min = @space.availables.recent.average(:minimum)
    cache.price_avg = @space.availables.recent.average(:price)
    cache.save
  end

Bonus:

I also read here:

http://m.onkey.org/active-record-query-interface

That the rails calculation methods average, sum, etc will be depreciated in 3.1, so should I'm unsure if I should be replacing them?

count(column, options)
average(column, options)
minimum(column, options)
maximum(column, options)
sum(column, options)
calculate(operation, column, options)
holden
  • 13,471
  • 22
  • 98
  • 160
  • you can try this create_or_update method: http://stackoverflow.com/questions/5578625/find-or-create-by-in-rails-3-and-updating-for-creating-records/5580108#5580108 – fl00r Apr 25 '11 at 21:44

1 Answers1

4

I wrote one for my has_one :event.

  def build_or_update_event(params)
    result = new_record? ? build_event(params) : event.update_attributes(params)
    result != false
  end
lulalala
  • 17,572
  • 15
  • 110
  • 169