前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Rails里实现Filter功能

Rails里实现Filter功能

作者头像
用户2183996
发布2018-06-28 10:49:41
3510
发布2018-06-28 10:49:41
举报
文章被收录于专栏:技术沉淀

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:

代码语言:javascript
复制
<%= 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:

代码语言:javascript
复制
#before
def index
    @posts = Post.all.order('created_at desc')
end
代码语言:javascript
复制
#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:

代码语言:javascript
复制
<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>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016.07.01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Scenario
  • Getting things done in rails
    • Routing
      • Controller
        • View
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档