【发布时间】: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