簡體   English   中英

在Rails4中,使用Trailblazer,如何訪問current_user

[英]In Rails4, using Trailblazer, how do I access the current_user

我們正在使用Trailblazer構建Rails4應用程序。 我之前從未與Trailblazer合作,我對如何做事感到困惑。

我們正在建立一個拍賣網站。 我以前使用傳統的控制器,這個路由端點工作正常:

 def bill    
     @profile = Profile.find_by user_id: current_user_id
     @current_order = Order.order(created_at: :desc).find_by(user_id: current_user_id)
     @batch = @current_order.batch

     if @batch.nil?
       puts "There was no batch linked to the current order of #{@current_order.id}"
       flash[:error] = "We are sorry, but we could not determine which batch your order belongs to."
     else
       @price_shown_to_customer = @batch.price + ENV["FUELBID_FEE_PER_GALLON"].to_f
       @amount = @current_order.quantity * @price_shown_to_customer
     end

但現在我想使用Representer類將其創建為Trailblazer api。

所以在routes.rb中我添加了一些“收費”:

 namespace :api do
   get '/price' => 'info#info'
   post '/order' => 'orders#create'
   get '/charges' => 'charges#bill'
 end

我創建了這個Api,但復制並粘貼了另一個:

 module Api
   class ChargesController < ApiApplicationController

     respond_to :json

     def bill
       respond_with OpenStruct.new.extend(ChargesRepresenter)
     end

   end
 end

我用一個簡單的Representsenter測試了上面的內容,一切正常,所以到目前為止一切都很好。 如果我從Representer返回簡單數據,那么我可以在這里看到它:

HTTP://本地主機:3000 / API / charges.json

但我需要獲得current_user。 這是怎么做到的? 現在,這不起作用:

 module ChargesRepresenter
   include Roar::JSON

   collection :price_shown_to_customer

   def price_shown_to_customer
     current_order = Order.order(created_at: :desc).find_by(user_id: current_user_id)
     puts "current_order"
     puts current_order.id
     batch = current_order.batch
     batch.price + ENV["FUELBID_FEE_PER_GALLON"].to_f  
   end
 end     

current_user_id存在於我的傳統控制器中,因為我們設置了Devise,因此我的傳統控制器繼承了它:

  class ChargesController < SecuredController

但有沒有辦法在Trailblazer Representsenter中獲得它?

希望這個答案還不算太晚。

  1. 如果您可以切換到Decorator模式而不是模塊。
  2. Representer真的不需要知道,也不關心它是從控制器或控制台調用還是測試。 它只需要一個哈希來構建你的json對象。 因此,您可以將另一個名為current_user_id的屬性傳遞給您的Representer,然后像您一樣在r presenter中使用它。

供參考:

如果您需要更快速的回復,您也可以將問題復制到https://gitter.im/trailblazer/chat 通常有幾個人在那里閑逛。 但是在這里為后代發一個問題也很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM