html或json的相同控制器操作中的不同代码

时间:2014-07-11 08:57:01

标签: ruby-on-rails actioncontroller

我有一个控制器动作,它以两种格式响应同一个根--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

组织它的最佳方法是什么?

2 个答案:

答案 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操作。