2012-01-27 25 views
0

我有三個字段USER_ID模型令牌時,沒有方法的錯誤,PRODUCT_IDunique_token。在控制器我實例化一個@token對象與user_id說明的product_id值從form.Then收集我打電話save_with_payment功能與該對象,函數內我要生成隨機字符串的3倍,並保存在unique_token場。問題是self.tokens.create!(unique_token: Digest::SHA1.hexdigest("random string"))給我都沒法錯誤undefined method tokens。什麼我在這裏做錯了嗎?澄清你T I要完成,我希望能夠檢索關聯到USER_IDPRODUCT_IDUser.find(1).tokensProduct.find(1).tokens .The模式相伴隨而產生unique_tokens的名單User has_many TokensProduct has_many Tokens注意:unique_token字段最初來自Token模型,user_id和product_id只是ref主鍵。很感謝!試圖調用函數實例化對象

def create 
    @token=Token.new(params[:token]) 
    if @token.save_with_payment 
    redirect_to :controller => "products", :action => "index" 
    else 
    redirect_to :action => "new" 
    end 
end 

class Token < ActiveRecord::Base 
    require 'digest/sha1' 

    def save_with_payment 
# if valid? 
# customer = Stripe::Charge.create(amount:buck,:currency => "usd",card:stripe_card_token,:description => "Charge for bucks") 
#self.stripe_customer_token = customer.id 
    3.times do 
     self.tokens.create!(unique_token: Digest::SHA1.hexdigest("random string")) 
    end 
    save! 
    end 
end 

回答

2

令牌類中沒有令牌方法。由於您創建了三個令牌,因此不需要@token實例。只需將save_with_payment作爲分類方法即可:

def create 
    if Token.save_with_payment(params[:token]) 
    redirect_to :controller => "products", :action => "index" 
    else 
    redirect_to :action => "new" 
    end 
end 

class Token < ActiveRecord::Base 
    require 'digest/sha1' 

    def self.save_with_payment(attributes) 
    attributes.merge!(unique_token: Digest::SHA1.hexdigest("foo")) 
    3.times do 
     self.create!(attributes) 
    end 
    end 

end 

希望這有助於您。

您可能還想將循環包裝在開始/救援中。否則,如果第二個或第三個創建!你最終失去了令牌並重定向到「新」。

對第一條評論的迴應: 如果您使用類方法,則不起作用。你不能稱有效?因爲你不在Token的實例的上下文中。我不建議堅持實例方法。如果你將其更改爲一個類的方法,你會想要將它包裝在一個事務塊:

def self.save_with_payment(attributes) 
    transaction do 
    attributes.merge!(unique_token: Digest::SHA1.hexdigest("foo")) 
    3.times do 
     self.create!(attributes) 
    end 
    rescue 
    false 
    end 
end 

這應該回滾SQL事務,如果任何的創造!調用失敗並將錯誤返回給控制器創建操作。

我會從令牌(令牌不應該關心創建/檢索客戶)拉出客戶代碼並將其放入控制器操作中。將相關信息傳遞到save_with_payments。像:

self.save_with_payments(customer, attributes) 
    ... 
end 
+0

這似乎是有益的,但它的代碼我以前那種intefere,如果你看一下上面我已經加入註釋掉的代碼,我不覺得有必要提前加,所以現在說未定義方法是否有效?。buck和stripe_card_token的值也來自表單(Token.new(params [; token]))。現在如何改變它? – katie 2012-01-27 23:20:22

相關問題