4

我目前使用查找或创建方法来更新我用来存储缓存信息的关联记录,但我想知道是否有一些更简单的替代方法类似于构建,因为对象是has_one关系。使用build_的问题在大多数情况下,对象将存在并需要更新。我可以使用一堆ifs检查,但是想知道是否有比我目前使用的更好的rails-fu。rails的构建或更新方法?

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 

奖励:

这里我也阅读:

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

但栏杆计算方法平均,总和等将在3.1贬值,所以应该我不确定如果我应该替换他们?

count(column, options) 
average(column, options) 
minimum(column, options) 
maximum(column, options) 
sum(column, options) 
calculate(operation, column, options) 
+0

你可以试试这个方法create_or_update:http://stackoverflow.com/questions/5578625/find-or-create-by-in-rails-3-and-updating-for-creating-records/5580108 #5580108 – fl00r 2011-04-25 21:44:24

回答

2

我为我写了一个has_one :event

def build_or_update_event(params) 
    result = new_record? ? build_event(params) : event.update_attributes(params) 
    result != false 
    end 
相关问题