有 2 张表,一张 topics,一张 topictexts
# models/topic.rb
class Topic < ApplicationRecord
has_one :topictext, dependent: :destroy
accepts_nested_attributes_for :posttext, allow_destroy: true, reject_if: :all_blank, update_only: true
end
# models/topictext.rb
class Topictext < ApplicationRecord
belongs_to :topic
end
class TopicsController < ApplicationController
def create
@topic.create(topic_params)
end
private
def topic_params
params.require(:topic).permit(:title, topictext_attributes: [:body])
end
end
第一种方法到这里就结束了
class ApplicationRecord < ActiveRecord::Base
after_save :trace_log
after_destroy :trace_log
def trace_log
if @_trigger_update_callback
after_on = 'update'
elsif @destroyed
after_on = 'destroy'
else
after_on = 'create'
end
puts "#{self.class.name}:#{after_on}"
end
end
因为不是每条 topic 都有 topictext,所有打算改一下依赖关系,直接通过 topictext_id 判断书否有 topictext。
# models/topic.rb
class Topic < ApplicationRecord
belongs_to :topictext, dependent: :destroy
accepts_nested_attributes_for :posttext, allow_destroy: true, reject_if: :all_blank, update_only: true
end
# models/topictext.rb
class Topictext < ApplicationRecord
has_one :topic, dependent: :nullify, optional: true
end
# 其余不变
但是在跟踪 class ApplicationRecord < ActiveRecord::Base
的 after_save
,发现 rails 进行了多一次操作
第二种方法:执行完后,多了下面 2 条操作,由于数据已经写入数据库,实际这 2 次操作,并没有任何影响。
源码也看了一下,找不到头绪,对于强迫症来说有点难受 :,有人了解其中原理吗?
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/nested_attributes.rb