在Rails中有兩種增加屬性的方法:我應該使用類或實例方法增加我的對象嗎?
實例級別:http://apidock.com/rails/ActiveRecord/Base/increment!
類級別:http://apidock.com/rails/ActiveRecord/Base/increment_counter/class
我想更新我的帖子模型上的計數器屬性,以保存帖子的評論數量。
對我的用例來說,這兩者中的哪一個更好?
我將使用它與PostgreSQL數據庫。
在Rails中有兩種增加屬性的方法:我應該使用類或實例方法增加我的對象嗎?
實例級別:http://apidock.com/rails/ActiveRecord/Base/increment!
類級別:http://apidock.com/rails/ActiveRecord/Base/increment_counter/class
我想更新我的帖子模型上的計數器屬性,以保存帖子的評論數量。
對我的用例來說,這兩者中的哪一個更好?
我將使用它與PostgreSQL數據庫。
出於您的目的,我認爲您應該在AR關聯中使用像:counter_cache
這樣的屬性。例如:
class Comment < ActiveRecord::Base
# cached value will stored into the comments_count column at posts table
belongs_to :post, counter_cache: true
end
class Post < ActiveRecord::Base
has_many :comments
end
Rails會在你不注意的情況下做很多工作。
對於上面提到的兩種方法(increcement_counter
和incresement
),它們用於不同的目的。 increcement_counter
是counter_cache
的魔術。 incresement
僅用於增加表中的某個整數值。
實例#increment_counter:更多的空中接力,並運行#update_all(快速,無驗證)。
很酷,我假設'counter_cache'列的類型是'integer'? – Numbers 2014-11-21 15:46:55
@數字當然 – achempion 2014-11-21 15:52:55