似乎我发现了一个错误。我有两个相似的模型,表现不同。
我有Post
模型 belongs_to Author
。
我有一个自我引用的Task
模型。
型号代码:
应用/模型/ 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
应用/模型/ task.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
但是尽管task_id
具有正确的父ID,但它是零。
为什么表现不同?