3

我们正在使用 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

我用一个简单的代表测试了上面的内容,一切都很好,所以到目前为止一切都很好。如果我从代表返回简单数据,那么我可以在这里看到它:

http://localhost: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 Representer 中获得它?

4

1 回答 1

1

希望这个答案还不算太晚。

  1. 如果您可以切换到装饰器模式而不是模块。
  2. 代表真的不需要知道也不关心它是从控制器、控制台还是测试中调用的。它所需要的只是一个哈希来构建您的 json 对象。因此,您可以将另一个名为 current_user_id 的属性传递给您的 Representer,然后像您一样在 r Presenter 中使用它。

供参考:

如果您需要更直接的回复,您也可以将您的问题复制到https://gitter.im/trailblazer/chat。通常有几个人在那里闲逛。但是在这里为后代发布一个问题也很好。

于 2015-11-29T21:28:45.633 回答