Browse files

Changed the Article#to_indexed_json to include data from associations

In the published version, special methods `Article#author_name` and `Article#comments_count` were added,
so we can display some data about authorship and comments from associations.

This would be less then ideal in a bigger codebase, and, moreover, Elasticsearch & Tire make it
trivial to support this use case.

The only thing we need to do is to `include` the selected information from the associated models
in the `Article#to_indexed_json` declaration.

In this way, the information about:

* Name of the article author
* Name of commenters and bodies of their comments

is included in the index. This has two benefits:

1. It's **searchable**! :) We can search within the comments in the same way as we do within articles.
2. We don't have to add special methods, and can revert the HTML layer to the original state.
  • Loading branch information...
1 parent 3910110 commit ee1f6f39002f32ad25134c81dd6de74ff1b708fa @karmi committed Dec 16, 2011
@@ -34,14 +34,7 @@ def
# self.include_root_in_json = false (necessary before Rails 3.1)
def to_indexed_json
- to_json(methods: [:author_name, :comments_count])
+ to_json( include: { comments: { only: [:content, :name] }, author: { only: [:name]} } )
- def author_name
- end
- def comments_count
- comments.size
- end
@@ -27,10 +27,10 @@
<% @articles.each do |article| %>
<%= link_to, article %>
- <span class="comments">(<%= pluralize(article.comments_count, 'comment') %>)</span>
+ <span class="comments">(<%= pluralize(article.comments.size, 'comment') %>)</span>
<div class="info">
- by <%= article.author_name %>
+ by <%= %>
on <%= article.published_at.to_time.strftime('%b %d, %Y') %>
<div class="content"><%= article.content %></div>

2 comments on commit ee1f6f3

would there be any changes to the "mapping" area?... can we still use author_name, comments_count there?


karmi replied Apr 2, 2012

Hi, no, this must be changed: see subsequent commit 03c45c3.

Please sign in to comment.