【问题标题】:rails build or update method?rails构建或更新方法?
【发布时间】:2011-08-08 11:12:42
【问题描述】:

我目前正在使用 find 或 create 方法来更新我用来存储缓存信息的关联记录,但我想知道是否有一些更简单的替代方法类似于 build,因为对象是 has_one 关系。仅使用 build_ 的问题是在大多数情况下该对象将存在并且需要更新。我可以使用一堆 ifs 检查,但想知道是否有比我目前使用的更好的 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

奖金:

我也在这里阅读:

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

rails 计算方法 average、sum 等会在 3.1 中贬值,所以我是否应该不确定是否应该替换它们?

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

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3 scope associations model-associations


【解决方案1】:

我为我的has_one :event写了一篇。

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

【讨论】:

    猜你喜欢
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2021-12-07
    • 2013-09-15
    • 2017-12-20
    • 1970-01-01
    相关资源
    最近更新 更多