这是我的代码
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.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