Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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...
commit ee1f6f39002f32ad25134c81dd6de74ff1b708fa 1 parent 3910110
@karmi authored
View
9 episode-307/blog-after/app/models/article.rb
@@ -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
View
4 episode-307/blog-after/app/views/articles/index.html.erb
@@ -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>

2 comments on commit ee1f6f3

@ipranay

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

@karmi
Owner

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

Please sign in to comment.
Something went wrong with that request. Please try again.