Skip to content

Commit cb6697c

Browse files
committed
Update Readme
add new relation_name option on associations and example
1 parent 634687c commit cb6697c

1 file changed

Lines changed: 21 additions & 1 deletion

File tree

README.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,9 @@ The association methods support the following options:
243243
* `foreign_key` - the method on the resource used to fetch the related resource. Defaults to `<resource_name>_id` for
244244
has_one and `<resource_name>_ids` for has_many relationships.
245245
* `acts_as_set` - allows the entire set of related records to be replaced in one operation. Defaults to false if not set.
246-
246+
* `relation_name` - the name of the relation to use on the model. A lambda may be provided which allows conditional
247+
selection of the relation based on the context.
248+
247249
Examples:
248250

249251
```ruby
@@ -264,6 +266,24 @@ class ExpenseEntryResource < JSONAPI::Resource
264266
end
265267
```
266268

269+
```ruby
270+
class BookResource < JSONAPI::Resource
271+
272+
# Only book_admins may see unapproved comments for a book. Using a lambda to select the correct relation on the model
273+
has_many :book_comments, relation_name: -> (options = {}) {
274+
context = options[:context]
275+
current_user = context ? context[:current_user] : nil
276+
277+
unless current_user && current_user.book_admin
278+
:approved_book_comments
279+
else
280+
:book_comments
281+
end
282+
}
283+
...
284+
end
285+
```
286+
267287
#### Filters
268288

269289
Filters for locating objects of the resource type are specified in the resource definition. Single filters can be

0 commit comments

Comments
 (0)