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 条评论
登录 后参与评论

相关文章

来自专栏Java Edge

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

3328
来自专栏Android 开发学习

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

2783
来自专栏我的博客

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

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

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

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

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

2425
来自专栏技术小黑屋

Issues About Installing Octopress

Actually I am fresh to Write Blog with Octopress in Github Pages.According to th...

902
来自专栏杨建荣的学习笔记

hotspare的copyback(r7笔记第30天)

最近做硬件巡检,发现一部分硬盘出现了坏块,同事就帮忙去协调处理这个事情,晚些时候接到了现场工程师的电话,问我可以不可以换,简单确认是raid5的盘。所以只能一个...

2975
来自专栏技术小黑屋

Package Stopped State Since Android 3.1

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

731
来自专栏ml

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

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

3326
来自专栏Golang语言社区

在GO中编写一个简单的shell

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

1195
来自专栏小鹏的专栏

ubuntu下CMake编译生成动态库和静态库,以OpenTLD为例。

opencv2.4.8,下载:Here. ubuntu下CMake编译生成动态库(.so)和静态库(.a),以OpenTLD为例。 直接看CMakeLists....

30610

扫码关注云+社区