Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何合并这两个def索引_Ruby On Rails - Fatal编程技术网

Ruby on rails 如何合并这两个def索引

Ruby on rails 如何合并这两个def索引,ruby-on-rails,Ruby On Rails,我有两个不同的索引操作,有人能帮我合并吗 第一个def索引(用于标记): 第二个def索引(针对类别): 我使用ransack进行过滤和排序: 设置起来很容易,并且可以实现您想要的功能。类似的功能就可以了 def index if params[:tag].present? @posts = Post.tagged_with(params[:tag]) elsif params[:category].present? @category = Category.find_b

我有两个不同的
索引
操作,有人能帮我合并吗

第一个def索引(用于标记):

第二个def索引(针对类别):


我使用ransack进行过滤和排序:


设置起来很容易,并且可以实现您想要的功能。

类似的功能就可以了

def index
  if params[:tag].present?
    @posts = Post.tagged_with(params[:tag])
  elsif params[:category].present?
    @category = Category.find_by_name(params[:category])
    @posts = @category.posts       
  else
    @posts = Post.all
  end
end

以下是一个简短的版本:

def index
  @posts =
    if params.key?(:tag)
      Post.tagged_with(params[:tag])
    elsif params.key?(:category)
      Post.joins(:categories).where(categories: { name: params[:category] })
    else
      Post.all
    end
end
然而,我想知道这种情况是否真的需要3种不同的路线和控制器:

# config/routes.rb
resources :categories, only: [] { resources :posts, only: :index }
resources :tags, only: [] { resources :posts, only: :index }
resources :posts, only: :index
然后

def index
  @posts =
    if params.key?(:tag)
      Post.tagged_with(params[:tag])
    elsif params.key?(:category)
      Post.joins(:categories).where(categories: { name: params[:category] })
    else
      Post.all
    end
end
# config/routes.rb
resources :categories, only: [] { resources :posts, only: :index }
resources :tags, only: [] { resources :posts, only: :index }
resources :posts, only: :index
# categories_posts_controller.rb
class CategoriesPostsController < ApplicationController
  def index
    @posts = Post.joins(:categories).where(categories: { id: params[:category_id] })
  end
end
# tags_posts_controller.rb
class TagsPostsController < ApplicationController
  def index
    @posts = Post.tagged_with(params[:tag_id])
  end
end
resources :categories, only: [] { resources :posts, only: :index, param: :name }