Ruby-on-rails .increment vs += 1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11499110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:41:45  来源:igfitidea点击:

.increment vs += 1

ruby-on-railsrubyincrement

提问by James Pleasant

I have a Picture model that contains a variable for a view count (integer). The view count is incremented by +1 every time someone views the Picture object.

我有一个包含视图计数(整数)变量的图片模型。每次有人查看图片对象时,查看计数都会增加 +1。

In getting this done, what is the difference between

在完成这项工作时,有什么区别

   @picture.view_count += 1
   @picture.save

and

   @picture.increment(:view_count, 1)

also if i use increment, is .save necessary?

另外,如果我使用增量,是否需要 .save ?

回答by xdazz

The source of incrementis below, which initializes attribute to zero if nil and adds the value passed as by (default is 1), it does not do save, so .saveis still necessary.

的来源increment如下,如果为nil,则将属性初始化为零并添加传递的值(默认为1),它不做保存,所以.save仍然是必要的。

def increment(attribute, by = 1)
  self[attribute] ||= 0
  self[attribute] += by
  self
end

回答by nekova

I often use counter_cacheand increment_counterin that case.

我经常使用counter_cacheincrement_counter在这种情况下。

like this:

像这样:

Picture.increment_counter(:view_count, @picture.id)

This way is more simple and faster than self-made method.

这种方法比自制方法更简单快捷。

Incidentally, ActiveRecord::CounterCache has also decrement_counter.

顺便说一下,ActiveRecord::CounterCache 也有decrement_counter.

http://api.rubyonrails.org/classes/ActiveRecord/CounterCache/ClassMethods.html

http://api.rubyonrails.org/classes/ActiveRecord/CounterCache/ClassMethods.html

回答by Vladimir Melnik

You should use counter_cache. counter_cache helps you increment number of records automaticaly.

您应该使用 counter_cache。counter_cache 帮助您自动增加记录数。

class Picture < ActiveRecord::Base
  has_many :views
end

class View < ActiveRecord::Base
  belongs_to :picture, counter_cache: true
end

pictures table needs column with name views_count, or you can use your own name for this column, for example:

图片表需要名为 views_count 的列,或者您可以为此列使用您自己的名称,例如:

belongs_to :picture, counter_cache: :number_of_views

But I recommend you to use default name for counter_cache column which is views_count.

但我建议您对 counter_cache 列使用默认名称,即 views_count。