Skip to content

Commit

Permalink
Changed the Article#to_indexed_json to include data from associations
Browse files Browse the repository at this point in the history
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
karmi committed Dec 16, 2011
1 parent 3910110 commit ee1f6f3
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 10 deletions.
9 changes: 1 addition & 8 deletions episode-307/blog-after/app/models/article.rb
Expand Up @@ -34,14 +34,7 @@ def self.search(params)

# 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]} } )
end

def author_name
author.name
end

def comments_count
comments.size
end
end
4 changes: 2 additions & 2 deletions episode-307/blog-after/app/views/articles/index.html.erb
Expand Up @@ -27,10 +27,10 @@
<% @articles.each do |article| %>
<h2>
<%= link_to article.name, article %>
<span class="comments">(<%= pluralize(article.comments_count, 'comment') %>)</span>
<span class="comments">(<%= pluralize(article.comments.size, 'comment') %>)</span>
</h2>
<div class="info">
by <%= article.author_name %>
by <%= article.author.name %>
on <%= article.published_at.to_time.strftime('%b %d, %Y') %>
</div>
<div class="content"><%= article.content %></div>
Expand Down

2 comments on commit ee1f6f3

@ipranay
Copy link

@ipranay ipranay commented on ee1f6f3 Apr 2, 2012

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@karmi
Copy link
Owner Author

@karmi karmi commented on ee1f6f3 Apr 2, 2012

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Please sign in to comment.