自我指涉模型的不同行为。这是一个错误吗?

时间:2014-10-24 09:16:42

标签: ruby-on-rails callback models self-referencing-table

似乎我发现了一个错误。我有两个相似的模型,表现不同。

我有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

PostTask的范围相似,但行为不同:

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,但它是零。

为什么表现不同?

0 个答案:

没有答案