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)
1.2 Object Relational Mapping Object Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With