Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails build or update method?

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)
like image 629
holden Avatar asked Apr 19 '11 07:04

holden


People also ask

What is ORM in ROR?

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.

What is ActiveRecord base?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What are callbacks in rails?

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.


1 Answers

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
like image 169
lulalala Avatar answered Oct 09 '22 12:10

lulalala