我收到了错误
HomeController中的NoMethodError #index未定义方法`id'代表nil:NilClass。
@id = params[:id]
@email = [:email]
if @id == @user.id && @email == @user.email
render :text => "sucsess"
else
render :text => "fail"
错误消息告诉我这些代码很奇怪。它说undefined method 'id'
,@id
似乎方法是@id == @user.id
吗?(我认为我定义@id
是可变的)
我该怎么办才能修复它?
home_controller
class HomeController < ApplicationController
def index
@id = params[:id]
@email = [:email]
if @id == @user.id && @email == @user.email
render :text => "成功"
else
render :text => "失敗"
end
end
def create
userData = UserData.new(create_params)
user = User.find(params[:id]).to_json
# エラー処理
unless userData.save
@error_message = [memo.errors.full_messages].compact
end
end
end
的routes.rb
Rails.application.routes.draw do
devise_for :users
root to: "home#index"
get 'home/index'
post 'home/index'
namespace :home, default: {format: :json} do
resources :index, only: :create
end
end
答案 0 :(得分:1)
HomeController中的NoMethodError #index未定义方法`id'代表nil:NilClass。
索引操作中的@user是nil
您需要先在索引操作或@user
before_filter
解决方案1
def index
@id = params[:id]
@email = [:email]
@user = User.find(params[:id]) # or current_user whatever your logic is
if @id == @user.id && @email == @user.email
render :text => "成功"
else
render :text => "失敗"
end
end
解决方案2
为before_filter
操作添加index
before_filter :find_user, only: [:index]
private
def find_user
@user = User.find(params[:id]) # or current_user implement this according to your logic
end
答案 1 :(得分:0)
您没有@user
的值,这就是为什么它表示未找到的方法id
。你必须具备以下价值:
@user = User.find(params[:id])
或
@user = User.first
在你的代码上:
def index
@user = User.first # defined User here like code on this line I added
@id = params[:id]
@email = [:email]
if @id == @user.id && @email == @user.email
render :text => "成功"
else
render :text => "失敗"
end
end
你应该确保你定义它。如果您有before_filter :your_method_define_user, only: [:index]
,请确保:your_method_define_user
的值为@user
。
正如上面写的@Deepak Mahakale。我想你很困惑。试试完整的代码:
<强>更新:强>
您的路线:
Rails.application.routes.draw do
devise_for :users
get 'home/index' # you must decide what to use post or get. But I use get here as default how index method is implemented in rails.
root to: "home#index"
end
你的控制器:
class HomeController < ApplicationController
before_filter :find_user, only: [:index]
def index
@id = params[:id]
@email = [:email]
if @id == @user.id && @email == @user.email
render :text => "成功"
else
render :text => "失敗"
end
end
def create
userData = UserData.new(create_params)
user = User.find(params[:id]).to_json
# エラー処理
unless userData.save
@error_message = [memo.errors.full_messages].compact
end
end
private
def find_user
@user = User.find(params[:id]) # You should specify this code what are your comparing to.
end
end
如果你使用get请求,你应该在url中传递参数,例如:
localhost:3000/home?id=<your_id>&email=<email_address>
如果帖子将其传递给表单中提供的字段。