rails build or update method?
Asked Answered
B

1

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)
Bekah answered 19/4, 2011 at 7:53 Comment(1)
you can try this create_or_update method: #5579125Redheaded
K
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
Kokura answered 26/3, 2012 at 12:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.