【问题标题】:In Rails4, using Trailblazer, how do I access the current_user在 Rails4 中,使用 Trailblazer,我如何访问 current_user
【发布时间】:2015-11-22 20:06:13
【问题描述】:

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

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

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 中获得它?

【问题讨论】:

  • 如果还不算太晚,我写了一个基于开拓者的 gem,我认为它更容易集成到现有的 rails 项目中,因为我的 gem 不需要你重新组织所有内容。结束于:github.com/NullVoxPopuli/skinny_controllers

标签: ruby-on-rails-4 trailblazer


【解决方案1】:

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

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

仅供参考:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多