我们正在使用 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 中获得它?