2016-05-20

Scenario

As a reader
When I click on category 'rails'
Then I should see articles of that category


If you want some practice, go for saas book’s RottenPotatoes demo. You will get a better understanding of filter and session stuff in rails! If you get stuck, you can have a look at my code as a poor reference, Lol, come here.

Getting things done in rails

Three points need to be considered. Routing, Controller and View(Since it’s very simple, we don’t need to resort to Model).

Routing

Make sure there is url mapped to desired controller#action(here we use index action), say there is a rails button to trigger this action. Code should look kind of like this:

<%= link_to "rails", posts_path(:category => 'rails') %>


As shown in the code, :category => 'rails' will be passed to params, which is handy.

Controller

In you post controller, change index action:

#before
def index
@posts = Post.all.order('created_at desc')
end

#after
def index
category = params[:category]
if category
@posts = Post.where("category = ?", category).order('created_at desc')
else
@posts = Post.all.order('created_at desc')
end
end


View

Since we use index action, there should be index.html.erb or index.html.haml. So we do not need to handle that. But it should looks somewhat like this:

<div id="posts_wrapper" class="skinny_wrapper">
<% @posts.each do |post| %>
<div class="post">
<p class="date"><%= post.created_at.strftime("%A, %B, %d") %></p>
<h2><a href="#"><%= link_to post.title, post %></a></h2>
<hr>
</div>
<% end %>
</div>