2014-04-04 61 views
1

我有以下控制器無法訪問控制器變量模型

class PaypalOrdersController < Spree::BaseController 

def new 
    @paypal_order = PaypalOrder.new 
end 

def create 
    @order1 = current_order 
    @paypal_order = PaypalOrder.new(params[:paypal_order]) 
    if @paypal_order.save 
     if @paypal_order.purchase 
     render :action => "success" 
     else 
     render :action => "failure" 
     end 
    else 
     render :action => "new" 
    end 
end 
end 

,對應的模式是:

class PaypalOrder < ActiveRecord::Base 
    require 'paypal_payment' 
    belongs_to :order 

    attr_accessor :card_number, :card_verification 

    validate :validate_card, :on => :create 

    def purchase 
    orderHash = @order1.clone 
    paypalHash = @paypal_order.clone 
    PaypalPayment.new(orderHash, paypalHash) 
    end 

    private 
    def validate_card 
    #some code 
    end 

    def credit_card 
    #some code 
    end 

end 

當觸發購買方法,我發現了錯誤cannot clone nil class。在調試時我發現@order1@paypal_order兩者在purchase方法中都是零。我不知道爲什麼會發生這種情況。請有人解釋。

感謝

回答

4

控制器:

PaypalOrder.purchase @order1, @paypal_order 

型號:

def self.purchase order, paypal_order 
orderHash = order.clone 
paypalHash = paypal_order.clone 
PaypalPayment.new(orderHash, paypalHash) 
end 

編輯: How do you pass data from a controller to a model with Ruby on Rails?

+0

是的,我明白,這是可以做到。但它不一定是。模型應該能夠訪問控制器變量,即使不傳遞它們。我不明白爲什麼變量在購買方法中爲零 – nish

+4

否,控制器變量不應在模型中可訪問。是的,有解決方法,但它打破了軌道的MVC概念。 –

0

試試這個

控制器

if @paypal_order.purchase @order1 

模型

def purchase order1 
    orderHash = order1.clone 
    paypalHash = self.clone   
    PaypalPayment.new(orderHash, paypalHash) 
end 
+0

這將工作。但這不應該需要。模型的方法應該能夠直接訪問控制器變量 – nish