Skip to content

Commit

Permalink
docs(README): add a section to explain changes propagation
Browse files Browse the repository at this point in the history
I was asked on support how to handle changes in nested children
and stumbled upon #40 and #74.
This PR aims to explain how to handle those.

I don't believe we'll have ever a way of detecting them, so:
Closes #74
  • Loading branch information
Jerska committed Jan 18, 2018
1 parent bd71a61 commit 1b8579b
Showing 1 changed file with 79 additions and 0 deletions.
79 changes: 79 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,8 @@ end

## Nested objects/relations

### Defining the relationship

You can easily embed nested objects defining an extra attribute returning any JSON-compliant object (an array or a hash or a combination of both).

```ruby
Expand All @@ -680,6 +682,83 @@ class Profile < ActiveRecord::Base
end
```

### Propagating the change from a nested child

#### With ActiveRecord

With ActiveRecord, we'll be using `touch` and `after_touch` to achieve this.

```ruby
# app/models/app.rb
class App < ApplicationRecord
include AlgoliaSearch

belongs_to :author, class_name: :User
after_touch :index!

algoliasearch do
attribute :title
attribute :author do
author.as_json
end
end
end

# app/models/user.rb
class User < ApplicationRecord
# If your association uses belongs_to
# - use `touch: true`
# - do not define an `after_save` hook
has_many :apps, foreign_key: :author_id

after_save { apps.each(&:touch) }
end
```


#### With Sequel

With Sequel, you can use the `touch` plugin to propagate the changes:

```ruby
# app/models/app.rb
class App < Sequel::Model
include AlgoliaSearch

many_to_one :author, class: :User

plugin :timestamps
plugin :touch

algoliasearch do
attribute :title
attribute :author do
author.to_hash
end
end
end

# app/models/user.rb
class User < Sequel::Model
one_to_many :apps, key: :author_id

plugin :timestamps
# Can't use the associations since it won't trigger the after_save
plugin :touch

# Define the associations that need to be touched here
# Less performant, but allows for the after_save hook to trigger
def touch_associations
apps.map(&:touch)
end

def touch
super
touch_associations
end
end
```

## Custom `objectID`

By default, the `objectID` is based on your record's `id`. You can change this behavior specifying the `:id` option (be sure to use a uniq field).
Expand Down

0 comments on commit 1b8579b

Please sign in to comment.