Rails里实现Filter功能

Scenario

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

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>

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏ml

HDUOJ----2952Counting Sheep

Counting Sheep Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/327...

35270
来自专栏CreateAMind

根据人类反馈进行强化学习+ 代码

https://github.com/nottombrown/rl-teacher

9910
来自专栏ml

poj-----Ultra-QuickSort(离散化+树状数组)

Ultra-QuickSort Time Limit: 7000MS Memory Limit: 65536K Total Submission...

38960
来自专栏技术小黑屋

Package Stopped State Since Android 3.1

Since Android 3.1, Android has introduced a LaunchControl mechanism. It’s call S...

11510
来自专栏JavaEdge

校园交易平台后台系统git操作全过程项目初始化用户模块完成

35680
来自专栏大数据学习笔记

Hadoop基础教程-第9章 HA高可用(9.3 HDFS 高可用运行)(草稿)

第9章 HA高可用 9.3 HDFS 高可用运行 9.3.1 HA节点规划 节点 IP Zookeeper NameNode JournalNode Da...

28950
来自专栏我的博客

Zend Framework自动加载、简单路由配置(Bootstrap.php)

<?php class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { /* * 自动加...

36580
来自专栏HansBug's Lab

1635: [Usaco2007 Jan]Tallest Cow 最高的牛

1635: [Usaco2007 Jan]Tallest Cow 最高的牛 Time Limit: 5 Sec  Memory Limit: 64 MB Sub...

33450
来自专栏Android 开发学习

Android studio 2.2 JNI ffmpeg 简单的播放器(这里只有视频解码)include "libavcodec/avcodec.h"include "libavformat/avf

58330
来自专栏Golang语言社区

在GO中编写一个简单的shell

In this post, we will write a minimalistic shell for UNIX(-like) operating syste...

14750

扫码关注云+社区

领取腾讯云代金券