Before_filter: authenticate_user!, кроме: [: index]/Rails 4
У меня есть Listings Controller
(Devise User System) и в Rails 3, который я использовал
before_filter :authenticate_user!, except: [:index]
чтобы проверить, был ли пользователь подписан перед просмотром определенного списка.
Моя домашняя страница (указатель) показывает внизу представление "Списки", Пользователь может их видеть, но как только он нажмет на нее, чтобы просмотреть ее, он перенаправляется на страницу входа.
Вот почему в моем контроллере я вместо
Listing.new -> current_user.listings.new
В Rails 4 вещи, похоже, изменились, и я не могу найти правильный способ сделать это.
Я немного искал и обнаружил, что команда была изменена на
before_action :authenticate_user!, :except => [:index]
Гость может просмотреть сейчас Индекс, но если он нажмет на Листинг, он не перенаправляется на страницу входа, вместо этого я получаю эту ошибку.
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.
Мой контроллер списков объявлений
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
РЕДАКТИРОВАТЬ: ПРОБЛЕМА 2
Если другой зарегистрированный пользователь пытается просмотреть список, который другой пользователь создал im, получая это →
![enter image description here]()
и log
![enter image description here]()
Ответы
Ответ 1
Попробуйте это, это позволит гостям увидеть список, указанный в параметре:
def set_listing
unless current_user
@listing = Listing.find(params[:id])
else
@listing = current_user.listings.find(params[:id])
end
end
Update:
Кажется, что вы хотите отображать списки по параметру, а не по current_user
. Если это так, пожалуйста, обновите определение set_listing
следующим образом:
def set_listing
@listing = Listing.find(params[:id]) if params[:id]
end
Ответ 2
Вызов authenticate_user
до set_listing
, так что current_user
не nil
before_action :authenticate_user!, :except => [:index]
before_action :set_listing, only: [:show, :edit, :update, :destroy]
Ответ 3
да
Вам нужно позвонить authenticate_user
до set_listing
, так что current_user
не nil
before_action :authenticate_user!, :except => [:index]
before_action :set_listing, only: [:show, :edit, :update, :destroy]
как это