我有一个控制器动作,它以两种格式响应同一个根--html和json。但是为html响应运行的代码与json响应的代码完全不同。 现在我有类似
的东西def index
result_html = ...
result_json = ...
respond_to |format|
format.html
format.json { result = result_json.limit(10) }
end
end
我希望像
一样 def index.html
result_html ...
end
和
def index.json
result_json ...
end
组织它的最佳方法是什么?
答案 0 :(得分:5)
这样的事情对你有用。
def index
respond_to |format|
format.html { index_html}
format.json { index_json }
end
end
def index_html
...
end
def index_json
...
end
答案 1 :(得分:1)
您可以使用request.format.symbol
测试格式,然后when :json
调用您的json操作或when :html
调用您的html操作。