0

It seems that I found a bug. I have two similar models that behave differently.

I have a Post model that belongs_to an Author.

I have a Task model that is self-referencing.

Model code:

app/models/author.rb:

class Author < ActiveRecord::Base
  has_many :posts
end

app/models/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

app/models/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

Both Post and Task are similarly scoped, but behave differently:

Author.create.posts.published.create    # works

Task.create.tasks.published.create      # doesn't work

Task.create.tasks.create                # works

There is an after_create callback in Task model, where it should print the parent Task but it is nil despite task_id having the correct ID of parent.

Why is it behaving differently?

Substantial
  • 6,684
  • 2
  • 31
  • 40
woto
  • 2,893
  • 1
  • 29
  • 24
  • 'task' association is nil. But 'task_id' is correct. – woto Oct 24 '14 at 09:32
  • Huh. Odd, seems to be a bug indeed. I get the following conditions on an associated model: `[["task_id", 3], ["status", 1], ["id", 3]]` and there's no way such model could exist with this logic. So, `task` association retains scopes: `Task#tasks` and `Task#published`. I wonder why. I'll dig into this, but you could as well get a gem `pry-rails`, place a `binding.pry` into your `after_create` and get to the source. I'll try as well. – D-side Oct 24 '14 at 10:17
  • @D-side pry is the yesterday :) already dig with it. – woto Oct 24 '14 at 10:51
  • The problem behavior seems to be a scoping issue inside the `after_create` callback. The association works fine after you refresh the child object. Everything works as expected so long as you don't attempt to load the association inside of the callback. – Substantial Oct 24 '14 at 13:10
  • Created [issue on github](https://github.com/rails/rails/issues/17382) – woto Oct 26 '14 at 10:16

0 Answers0