Ruby on Rails:显示所有帖子的弹性搜索

时间:2015-11-01 18:51:46

标签: ruby-on-rails elasticsearch rubygems

我添加了弹性搜索gem并在导航栏上添加了搜索按钮,但是,当我希望用户搜索帖子时,它会要求我登录或注册。我希望用户能够查看帖子的索引页面,我在posts_controller文件中添加了一个before_filter,但我不知道为什么它一直要求我注册或登录。这是我的代码:

posts_controller.rb

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user! , except: [:index,:show]
  before_filter :check_user, only: [:edit,:update,:destroy]



  # GET /posts
  # GET /posts.json

  def search
    if params[:search].present?
    @posts = Post.search(params[:search])
    else
    @posts = Post.all
    end
  end

  def index
    if params[:tag]
      @posts = Post.tagged_with(params[:tag])
    else
      @posts = Post.all
    end
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
    @reviews = Review.where(post_id: @post.id)
  end

  # GET /posts/new
  def new
    @post = Post.new
  end


  # GET /posts/1/edit
  def edit
    @post = Post.find(params[:id])
  end

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)
    @post.user_id = current_user.id

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to root_url, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post.destroy
    respond_to do |format|
      format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
      params.require(:post).permit(:title, :description,:image,:all_tags)
    end

    def check_user
      if  current_user.id != @post.user_id
      redirect_to root_path , alert: "Sorry this Post belongs to someone else"
    end
    end

end

2 个答案:

答案 0 :(得分:0)

您可以使用

skip_before_filter :authenticate_user! , :only => [:index,:show]
在你的控制器中

跳过before_filter来执行这些操作。

答案 1 :(得分:0)

我能够通过将搜索方法添加到before_action post认证来解决问题。这是代码:

  before_action :authenticate_user! , except: [:index,:show,:search]