Rails 构建或更新方法?

发布于 2024-11-02 02:36:14 字数 934 浏览 7 评论 0原文

我目前正在使用 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)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

溺渁∝ 2024-11-09 02:36:14

我为我的 has_one :event 编写了一个。

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文