0

バグを発見したようです。異なる動作をする 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_createTask モデルにはコールバックがあり、親を出力する必要がありますが、親の正しい ID があるに Taskもかかわらず nilです。task_id

なぜ動作が異なるのですか?

4

0 に答える 0