我们正在使用 Trailblazer 构建 Rails4 应用程序。我以前从未与 Trailblazer 合作过,我对如何做事感到困惑。
我们正在 build 一个拍卖网站。我之前使用的是传统 Controller ,这个路由端点运行良好:
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 测试了上面的内容,一切正常,所以到目前为止一切都很好。如果我从 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 存在于我的传统 Controller 中,因为我们设置了 Devise,所以我的传统 Controller 继承了它:
class ChargesController < SecuredController
但是有什么方法可以在 Trailblazer Representer 中获取它吗?
最佳答案
希望这个答案还不算太晚。
- 如果您可以切换到装饰器模式而不是模块。
- Representer 真的不需要知道也不关心它是从 Controller 、控制台还是测试调用的。它所需要的只是一个哈希来构建你的 json 对象。因此,您可以将另一个名为 current_user_id 的属性传递给您的 Representer,然后像您一样在 r presenter 中使用它。
仅供引用:
如果您需要更直接的回复,您也可以将您的问题复制到 https://gitter.im/trailblazer/chat .通常有几个人在那里闲逛。但在这里为后代提出问题也很好。
关于ruby-on-rails-4 - 在 Rails4 中,使用 Trailblazer,如何访问 current_user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33859556/