Ruby on rails 是否可以将计数器\u缓存与存储\u访问器一起使用?
我有一个(Ruby on rails 是否可以将计数器\u缓存与存储\u访问器一起使用?,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,我有一个(数据),我为它定义了如下属性: class Post < ApplicationRecord has_many :comments store_accessor :data, :comments_count end class Comment < ApplicationRecord belongs_to :post, counter_cache: true end class Post
数据
),我为它定义了如下属性:
class Post < ApplicationRecord
has_many :comments
store_accessor :data, :comments_count
end
class Comment < ApplicationRecord
belongs_to :post, counter_cache: true
end
class Post
是否有任何方法可以使用Rails的计数器缓存,将计数保存在根据上述定义的属性中?请记住,存储存取器是用于存储的。如果您要定义您的商店,您应该使用以下内容:
class Post < ApplicationRecord
store :data, :comments_count
# store :data, accessors: [ :comments_count ], coder: JSON
end
class Post
您需要指定关联大小的计数器缓存
我没试过这个,但这个怎么样
class Comment < ApplicationRecord
belongs_to :post, counter_cache: :comments_count
end
class注释
编辑:
或
class注释
请记住,存储存取器是用于存储的。如果您要定义您的商店,您应该使用以下内容:
class Post < ApplicationRecord
store :data, :comments_count
# store :data, accessors: [ :comments_count ], coder: JSON
end
class Post
您需要指定关联大小的计数器缓存
我没试过这个,但这个怎么样
class Comment < ApplicationRecord
belongs_to :post, counter_cache: :comments_count
end
class注释
编辑:
或
class注释
您的第一个建议给出了以下错误“NameError:undefined local variable or method`data'for#”。第二个建议是以下错误:“TypeError:没有将符号隐式转换为整数”。顺便问一下,您的意思是使用store\u访问器
是不正确的吗?您的商店
示例是否更适合我?您是否查看了文档?您希望如何访问注释数?post.comments\u count或post.data[:comments\u count]?这其实并不重要,但使用store\u accessor
我习惯于直接使用该属性,即post.comments\u count
。您的第一个建议给出了以下错误“NameError:未定义的局部变量或方法`数据'”。第二个建议是以下错误:“TypeError:没有将符号隐式转换为整数”。顺便问一下,您的意思是使用store\u访问器
是不正确的吗?您的商店
示例是否更适合我?您是否查看了文档?您希望如何访问注释数?post.comments\u count或post.data[:comments\u count]?这其实并不重要,但使用store\u accessor
我习惯于直接使用该属性,即post.comments\u count
。