【发布时间】:2016-11-09 01:35:15
【问题描述】:
我有一个 after_initialize 方法,它应该在 Conference 初始化时创建 2 个子记录,但它正在创建 8 个(每个 4 个)。这似乎不是多线程错误,但我不确定。
conference.rb
class Conference < ApplicationRecord
has_many :tracks, dependent: :destroy
after_initialize do
initialize_tracks
end
private
def initialize_tracks
one = Track.new(name: 'Track One')
two = Track.new(name: 'Track Two')
tracks << one
tracks << two
end
end
conference_controller#create
def create
@conference = Conference.new(conference_params)
respond_to do |format|
if @conference.save
# lines = input_file.read.split(/\n/)
# lines.each do |line|
# next if line.blank?
# title, length = line.split(/\d|lightning/)
# length = '5min' if length.nil?
# @conference.tracks.first.talks << Talk.new(title: title, length: length.scan(/\d/).first)
# end
format.html { redirect_to @conference, notice: 'Conference was successfully created.' }
format.json { render :show, status: :created, location: @conference }
else
format.html { render :new }
format.json { render json: @conference.errors, status: :unprocessable_entity }
end
end
end
track.rb
# == Schema Information
#
# Table name: tracks
#
# id :integer not null, primary key
# conference_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# name :string
#
class Track < ApplicationRecord
belongs_to :conference
has_many :talks, dependent: :destroy
end
【问题讨论】:
-
试试 Track.skip_callback(:after_initialize)
标签: ruby-on-rails activerecord ruby-on-rails-5 activemodel