我一直在搜索遍地,無法找到任何地方的答案。NoMethodError Rails 3.2
我正在參加RoR課程的udemy課程介紹,我已經能夠解決我在課程的前80%所遇到的所有問題,但現在我在路障中,可以找不到這個。我們正在構建一個類似Etsy的應用程序,而且我正需要限制用戶編輯/刪除不屬於他們的列表。
我on Rails的Ruby的運行3.2.21 1.9.3
我嘗試以下,用於將檢查用戶過濾器的指令,但是當我檢查回本地主機上,我收到此錯誤:
NoMethodError in ListingsController#edit
undefined method `user' for nil:NilClass
app/controllers/listings_controller.rb:98:in `check_user'
Parameters: {"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
如果需要任何其他信息,以幫助回答這個問題,請讓我知道。
太謝謝你了!我一直在努力解決這個問題。由於某種原因,教師的代碼自動調用'set_listing',所以我不知道我需要將其輸入到我的代碼中。 只要StackOverflow允許,我會在幾分鐘內將您的答案標記爲已接受。 – 2015-04-03 19:18:27
不客氣。 – smathy 2015-04-03 19:25:34