这是我的代码
class Project < ActiveRecord::Base
has_many :actions
end
class Action < ActiveRecord::Base
belongs_to :project, counter_cache: true
end
这是我的架构:
create_table "actions", :force => true do |t|
t.string "name"
t.integer "position", :default => 0
t.integer "project_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "projects", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "actions_count", :default => 0
end
我的问题是,在创建项目的第一个Action之后,project.actions_count仍为0.但是,当我创建第二个Action时,它会递增到1.发生了什么?为什么它会第一次跳过?
我尝试了多种创建Action的方法:
action = Action.new(params[:action_event])
action.save
action = Action.create(params[:action_event])
project = Project.find(params[:action_event][:project_id])
action = project.actions.create(params[:action_event])
有什么想法吗?
更新
以下是日志中递增actions_count:
的行首先:SQL (0.5ms) UPDATE "projects" SET "actions_count" = COALESCE("actions_count", 0) + 1 WHERE "projects"."id" = 64
第二:SQL (0.3ms) UPDATE "projects" SET "actions_count" = COALESCE("actions_count", 0) + 1 WHERE "projects"."id" = 64
答案 0 :(得分:0)
在检查project.reload
的值之前调用actions_count
就是我所需要的。