如何按类别进行搜索?

时间:2015-03-10 11:36:12

标签: ruby-on-rails

我有两个模型postcategory与habtm关联。如何在查询中运行在posts_controller中的index操作中?

点击某些类别的某个类别,她会在相同的操作中返回这些类别中的样本位置。

class PostsController < ApplicationController
  def index
    @posts = Post.where(status: true)
    @categories = Category.all
  end

UPD

index.html.slim

.col-md-8
  - @posts.each do |post|
    h2 = link_to post.title, post_path(post)
    = post.description
    p = sanitize post.body
.col-md-4
  - @categories.each do |category|
    h4 = link_to category.name, category_path(category)

1 个答案:

答案 0 :(得分:0)

= link_to category.name, {:controller => "controllername", :action => "index", :search=> category.name}

在表单中添加搜索字段,并使用某个字符串调用相同的index操作, 然后在控制器

def index
   if params[:search]
       @categories = Category.where(name: params[:search])
   else
        @posts = Post.where(status: true)
        @categories = Category.all   
   end
end