Ruby-on-rails before_filter :authenticate_user!, 除了: [:index] / Rails 4

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17911046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:24:57  来源:igfitidea点击:

before_filter :authenticate_user!, except: [:index] / Rails 4

ruby-on-railsauthenticationdeviseruby-on-rails-4

提问by Mini John

I Have a Listings Controller(Devise User System) and in Rails 3i just used

我有一个Listings Controller(设计用户系统)并且在Rails 3 中我刚刚使用

before_filter :authenticate_user!, except: [:index]

to check if a user was signed in before viewing a specific listing.

在查看特定列表之前检查用户是否已登录。

My Homepage (Index) shows at the bottom a view Listings, the User is able to see them, but as soon as he clicks on one to view it he is redirected to the Login Page.

我的主页(索引)在底部显示一个视图列表,用户可以看到它们,但是一旦他点击一个查看它,他就会被重定向到登录页面。

That's why in my controller i had instead of

这就是为什么在我的控制器中我有而不是

Listing.new -> current_user.listings.new

In Rails 4things seems to have changed and i cant find the right way to do it.

Rails 4 中,事情似乎发生了变化,我找不到正确的方法来做到这一点。

I searched a little bit and found that the command was changed to

我稍微搜索了一下,发现命令改为

before_action :authenticate_user!, :except => [:index]

A Guest can view now the Index but if he clicks on a Listing, he is not redirected to the login page, instead i get this error.

客人现在可以查看索引,但如果他单击列表,他不会重定向到登录页面,而是出现此错误。

NoMethodError in ListingsController#show
undefined method `listings' for nil:NilClass

# Use callbacks to share common setup or constraints between actions.
def set_listing
        @listing = current_user.listings.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.

My Listings Controller

我的房源控制器

class ListingsController < ApplicationController
  before_action :set_listing, only: [:show, :edit, :update, :destroy]
    before_action :authenticate_user!, :except => [:index]

  # GET /listings
  # GET /listings.json
  def index
    @listings = Listing.order("created_at desc")
  end

  # GET /listings/1
  # GET /listings/1.json
  def show
  end

  # GET /listings/new
  def new
        @listing = current_user.listings.build
  end

  # GET /listings/1/edit
  def edit
  end

  # POST /listings
  # POST /listings.json
  def create
        @listing = current_user.listings.build(listing_params)

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

  # PATCH/PUT /listings/1
  # PATCH/PUT /listings/1.json
  def update
    respond_to do |format|
      if @listing.update(listing_params)
        format.html { redirect_to @listing, notice: 'Listing was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @listing.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /listings/1
  # DELETE /listings/1.json
  def destroy
    @listing.destroy
    respond_to do |format|
      format.html { redirect_to listings_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_listing
            @listing = current_user.listings.find(params[:id])
    end

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

EDIT: PROBLEM 2

编辑:问题 2

If another Logged in User tries to view a listing which another User created im getting this ->

如果另一个登录用户试图查看另一个用户创建的列表,我会得到这个 ->

enter image description here

在此处输入图片说明

and the log

和日志

enter image description here

在此处输入图片说明

采纳答案by vee

Try this, this will allow guests to see listing supplied in the parameter:

试试这个,这将允许客人看到参数中提供的列表:

def set_listing
    unless current_user
        @listing = Listing.find(params[:id])
    else
        @listing = current_user.listings.find(params[:id])
    end
end

Update:

更新:

It appears that you want to display listings by parameter and not by the current_user. If so then please update your set_listingdefinition as follows:

看来您想按参数而不是按current_user. 如果是这样,请set_listing按如下方式更新您的定义:

def set_listing
    @listing = Listing.find(params[:id]) if params[:id]
end

回答by Santhosh

Call authenticate_userbefore set_listing, so that current_useris not nil

authenticate_user之前调用set_listing,所以current_user不是nil

before_action :authenticate_user!, :except => [:index]
before_action :set_listing, only: [:show, :edit, :update, :destroy]

回答by shubham dubey

before_filter :authenticate_user!, except: [:index]

before_filter :authenticate_user!, except: [:index]

this is used when we want to redirect users to particular page when the user is not logged in.

当我们想在用户未登录时将用户重定向到特定页面时使用。

in this ",except[:index]"where the index is pagename of Htmlview where you want to redirect the user.

在此",except[:index]"索引是Html您要重定向用户的视图的页面名称。

回答by sumit

yes You need to call authenticate_userbefore set_listing, so that current_useris not nil

是的,你打电话authenticate_user之前set_listing,这样current_user是不是nil

before_action :authenticate_user!, :except => [:index]
before_action :set_listing, only: [:show, :edit, :update, :destroy]

like this

像这样