【发布时间】:2015-04-03 19:09:35
【问题描述】:
我一直在寻找,在任何地方都找不到答案。
我正在学习关于 udemy 的 RoR 课程的介绍,并且我已经能够解决我在课程的前 80% 中遇到的所有问题,但现在我遇到了障碍并且无法找不到这个。我们正在构建一个像 Etsy 这样的应用程序,我需要限制用户编辑/删除不属于他们的列表。
我在 Rails 3.2.21 上运行 Ruby 1.9.3
我尝试按照说明添加检查用户过滤器,但是当我重新检查本地主机时,收到此错误:
ListingsController 中的 NoMethodError#edit
nil:NilClass 的未定义方法“用户”
app/controllers/listings_controller.rb:98:in `check_user'
参数: {"id"=>"8"}
我的代码与讲师的代码完全匹配,但我认为这个错误是因为我使用的是 Rails 3,而他使用的是 4。
这是我的 listings_controller.rb
class ListingsController < ApplicationController
# GET /listings
# GET /listings.json
before_filter :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
before_filter :check_user, only: [:edit, :update, :destroy]
def index
@listings = Listing.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @listings }
end
end
# GET /listings/1
# GET /listings/1.json
def show
@listing = Listing.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @listing }
end
end
# GET /listings/new
# GET /listings/new.json
def new
@listing = Listing.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @listing }
end
end
# GET /listings/1/edit
def edit
@listing = Listing.find(params[:id])
end
# POST /listings
# POST /listings.json
def create
@listing = Listing.new(params[:listing])
@listing.user_id = current_user.id
respond_to do |format|
if @listing.save
format.html { redirect_to @listing, notice: 'Listing was successfully created.' }
format.json { render json: @listing, status: :created, location: @listing }
else
format.html { render action: "new" }
format.json { render json: @listing.errors, status: :unprocessable_entity }
end
end
end
# PUT /listings/1
# PUT /listings/1.json
def update
@listing = Listing.find(params[:id])
respond_to do |format|
if @listing.update_attributes(params[:listing])
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 = Listing.find(params[:id])
@listing.destroy
respond_to do |format|
format.html { redirect_to listings_url }
format.json { head :no_content }
end
end
private
def set_listing
@listing = Listing.find(params[:id])
end
def listing_params
params.require(:listing).permit(:name, :description, :price, :image)
end
def check_user
if current_user != @listing.user
redirect_to root_url, alert: "Sorry, this listing belongs to someone else."
end
end
end
为此我们必须添加的代码是第二个 before_filter 和 def check_user
如果需要任何其他信息来帮助回答这个问题,请告诉我。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 nomethoderror