Noah
Noah

Reputation: 410

Rails after_add association callback not triggering

On my model, I have the line below included:

has_many :notes, as: :notable, dependent: :destroy, after_add: :create_informal_note

When I create a note associated to the model where the line above resides, I expect the create_informal_note method to fire.

However, the method is not being fired.

What's wrong here?

Potential Problem:

The note is being created from a HTTP request to POST /api/v1/notes. In the request body's JSON, it includes notable_id and notable_type. It's setting the actual fields, not setting notable as an object.

POST /api/v1/notes

{
  "note": {
    "text": "Test note",
    "notable_id": 1,
    "notable_type": "AnotherModel"
  }
}

And the output logs from my running Rails web server:

Processing by NotesController#create as JSON
  Parameters: {"note"=>{"notable_id"=>"1", "notable_type"=>"AnotherModel", "text"=>"Test note", "email"=>1, "documents_attributes"=>nil}}
   (0.2ms)  BEGIN
  SQL (2.0ms)  INSERT INTO `notes` (`text`, `notable_id`, `notable_type`, `created_at`, `updated_at`) VALUES ('Test note', 1, 'AnotherModel', '2016-02-19 11:32:56.401216', '2016-02-19 11:32:56.401216')
   (1.1ms)  COMMIT

Could Rails be ignoring the association and hence the callback not triggering due to this?

Upvotes: 1

Views: 2511

Answers (2)

davidpm4
davidpm4

Reputation: 582

Might be worth pointing out to future readers that this functionality is documented in the Active Record docs: https://guides.rubyonrails.org/association_basics.html#association-callbacks

# These callbacks are called only when the associated objects 
# are added or removed through the association collection:


# Triggers `before_add` callback
author.books << book
author.books = [book, book2]

# Does not trigger the `before_add` callback
book.update(author_id: 1)

Upvotes: 2

Gabriel
Gabriel

Reputation: 169

This callback only works when adding the association via the << as per Mareq's comment above and the thread he mentioned.

Upvotes: 3

Related Questions