我的控制器中有以下方法
around_action :wrap_in_transaction_and_begin, only: :update
def wrap_in_transaction_and_begin
ActiveRecord::Base.transaction do
begin
render json: yield
rescue => e
ActiveRecord::Rollback
render json: { error: e.to_s }
end
end
end
但问题是引发了一个错误,因为rails希望在方法更新中使用 "render",而不是在action_around中使用,但我需要在方法更新的返回值中使用render json。
Missing template topics/update...
因为rails希望在方法更新中使用 "render",而不是action_around.但我需要在方法更新的返回值中使用render json。
举个例子。
def update
hash = { foo: :bar }
topic.update(hash)
hash
end
我想在json中渲染hash对象。
我如何才能做到这一点?
thx.
这里有很多错误的地方,主要是因为你从Rails应该如何工作的角度出发,进入了不支持的工作流。
首先,动作的返回值没有用。Rails 并不希望你的操作返回任何东西,而且它也不需要 做 任何与返回值相关的内容。Rails希望你的动作的输出是一个或者是一个 render
或重定向,如果你不做这两件事,你就等于让Rails为你做渲染。这就是为什么Rails试图渲染 topics/update
.
你还误用了周围的过滤器。它们的目的是转换你的动作的输出,而不是由输出的唯一生成器。
你应该渲染JSON的方式是使用 respond_with
从你的行动中。首先,使用 respond_to
来定义你的控制器可以输出的数据种类......。
class MyController < ApplicationController
respond_to :json
end
然后,用你想要的值进行响应。
def update
hash = { foo: :bar }
topic.update(hash)
respond_with hash
end