Ruby on rails rails构建还是更新方法?
我目前正在使用find或create方法来更新用于存储缓存信息的关联记录,但我想知道是否有类似于build的更简单的替代方法,因为对象是一个Ruby on rails rails构建还是更新方法?,ruby-on-rails,ruby-on-rails-3,scope,associations,model-associations,Ruby On Rails,Ruby On Rails 3,Scope,Associations,Model Associations,我目前正在使用find或create方法来更新用于存储缓存信息的关联记录,但我想知道是否有类似于build的更简单的替代方法,因为对象是一个有一个关系。仅使用build_uu的问题是,在大多数情况下,对象将存在并且需要更新。我可以用一大堆的如果来检查,但是我想知道是否有比我现在使用的更好的rails fu def self.update_caches(data) cache = SpaceCache.find_or_create_by_space_id(@space.id)
有一个关系。仅使用build_uu的问题是,在大多数情况下,对象将存在并且需要更新。我可以用一大堆的如果来检查,但是我想知道是否有比我现在使用的更好的rails fu
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
奖金:
我也在这里读到:
rails计算方法average、sum等将在3.1中折旧,因此我是否应该确定是否应该替换它们
count(column, options)
average(column, options)
minimum(column, options)
maximum(column, options)
sum(column, options)
calculate(operation, column, options)
我为我的has\u one:event
写了一个
def build_or_update_event(params)
result = new_record? ? build_event(params) : event.update_attributes(params)
result != false
end
您可以尝试此创建\u或\u更新方法: