Rails重定向会话变量

时间:2013-11-20 01:15:24

标签: ruby-on-rails

我有一个看起来像这样的着陆页控制器;

class LandingController < ApplicationController
    def index
        @user = current_user
        @name = @user.name.titleize

        @balance = "#{@user.currency} #{@user.balance}"

        @last_login = @user.last_sign_in_at

        api_key = ApiKey.find_by_user_id( @user.id)
        @access_token = api_key.access_token


    end

    def check_mail


    end

end

但是,在下面显示的控制器方法中,当我进行重定向时,我收到错误。

控制器方法;

def success   
        transaction = Transaction.find_by_token(params[:token])
        transaction.payer_id = params[:payer_id] 
        transaction.save
        @current_user = user = User.find(transaction.user_id)   
        username = "xxxxxxxxxxxxxxxxxxxx"
        password = "7xxxxxxxxxxxxxxx"
        signature = "xxxxxxxxxxxxxxx"       
        version = 98
        @amount = Currency.convert(user.currency, "USD", transaction.amount.to_f).to_f.round(2)
        url = "https://api-3t.paypal.com/nvp?USER=#{username}&PWD=#{password}&SIGNATURE=#{signature}&VERSION=#{version}&METHOD=DoExpressCheckoutPayment&TOKEN=#{transaction.token}&PAYERID=#{transaction.payer_id}&PAYMENTREQUEST_0_PAYMENTACTION=SALE&PAYMENTREQUEST_0_AMT=#{@amount}&PAYMENTREQUEST_0_CURRENCYCODE=USD"       
        uri = URI.parse(url)
        http = Net::HTTP.new(uri.host, uri.port)
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE 
        request = Net::HTTP::Get.new(uri.request_uri)
        res = http.request(request)
        response = res.body
        transaction.save
        user.balance = (user.balance+transaction.amount)
        user.save()         
        transaction.status ="Completed"
        transaction.save()  
        flash[:notice] = 'Payment Transaction Completed. Thank you for using skyline SMS'
        redirect_to user_home_path(@current_user)     
    end

我收到以下错误;

undefined method `name' for nil:NilClass

跟踪;

app/controllers/landing_controller.rb:4:in `index'

我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

问题是LandingController中的@user变量没有值(它是nil),这就是你为nil:class获取未定义方法名称的原因,试试这个:把这个重定向放到这里

    #stuff...
    redirect_to user_home_path(:current_user => @current_user)
 end

并在LandingController索引中放了这个

def index
    @user = params[:current_user]
    @name = @user.name.titleize
#...rest of the method...