上周我在Job 模型上实现了一个:view_count 整数列。今天我正在比较我的网站和谷歌分析之间的统计数据。综合浏览量的数字不一致(有时相差甚远),我现在怀疑我是否搞砸了这个简单的任务。
另一个复杂的问题是此操作中的某些条件逻辑。如果有人想提出任何更改建议,我愿意接受一种更好的方式来编写整个操作。
def show
unless signed_in?
redirect_to jobs_path, status: 301, if @job.end_date < Time.zone.now.to_date
@job.increment! :view_count unless @job.end_date < Time.zone.now.to_date
end
end
查看 API 文档后,我考虑将以下行重写为:
Job.increment_counter(:view_count, @job) unless @job.end_date < Time.zone.now.to_date
那么。
1) 跳出来有什么问题吗?
2)哪个更好用:增量!或增量计数器。
我正在为数据库使用 Postgres。任何有帮助的建议或想法都将受到赞赏。
注意:在@job = Job.find(params[:id]) 上使用before_filter
最佳答案
有什么不对的地方跳出来了吗?是的,increment!
完全错误,不应使用恕我直言。我为什么这么说?与 Rails 一样,您必须阅读源代码才能了解发生了什么。这就是increment!
做:
def increment!(attribute, by = 1)
increment(attribute, by).update_attribute(attribute, self[attribute])
end
increment
有什么作用? increment
这样做:
def increment(attribute, by = 1)
self[attribute] ||= 0
self[attribute] += by
self
end
和update_attribute
这样做:
def update_attribute(name, value)
name = name.to_s
raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
send("#{name}=", value)
save(:validate => false)
end
展开它,我们看到您的 @job.increment! :view_count
与此相同:
@job.view_count = (@job.view_count || 0) + 1
@job.save(:validate => false)
这里的竞争条件应该很清楚:
- Process-1 加载
@job
。 - Process-2 加载相同的
@job
。 - Process-1 递增
@job.view_count
并将其写入数据库。 - Process-2 递增
@job.view_count
并将其写入数据库。
但是 Process-2 不知道 Process-1 在其背后增加了 view_count
,因此 Process-1 的增量消失了。所以,是的,increment!
非常愚蠢并且容易丢失数据,我不会将它用于任何事情。
如果你追踪 increment_counter
你会看到它只是 update_counters
的包装器.如果您阅读 update_counters
,您会发现它通过简单地告诉数据库使用 SQL 增加列值来正确地让数据库完成工作,大致如下所示:
update t set c = c + 1 where id = x
这应该是可靠的。
总结:忘记 increment!
, decrement!
, increment
, and decrement!
存在并使用 increment_counter
代替。
关于ruby - 偏执一个增量!计数器可能无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24211028/