バグを発見したようです。異なる動作をする 2 つの類似したモデルがあります。
私は属しているPost
モデルを持っていAuthor
ます。
Task
自己参照するモデルがあります。
モデルコード:
app/models/author.rb :
class Author < ActiveRecord::Base
has_many :posts
end
アプリ/モデル/post.rb :
class Post < ActiveRecord::Base
belongs_to :author
scope :published, -> { where(status: 1) }
after_create do
puts '========================================='
puts "author_id is present: '#{author_id}'"
puts "what about task association? '#{author}'"
puts '========================================='
end
end
アプリ/モデル/タスク.rb :
class Task < ActiveRecord::Base
belongs_to :task
has_many :tasks
scope :published, -> { where(status: 1) }
after_create do
puts '========================================='
puts "task_id is present: '#{task_id}'"
puts "what about task association? '#{task}'"
puts '========================================='
end
end
Post
とのTask
スコープは似ていますが、動作が異なります。
Author.create.posts.published.create # works
Task.create.tasks.published.create # doesn't work
Task.create.tasks.create # works
after_create
Task モデルにはコールバックがあり、親を出力する必要がありますが、親の正しい ID があるに Task
もかかわらず nilです。task_id
なぜ動作が異なるのですか?