0

我有以下代码段

def range
  respond_to do |format|
    if params[:start] && params[:end]
      begin
        dstart = Time.parse(params[:start])
        dend = Time.parse(params[:end])
      rescue => e
        format.json { render :json => { :status => :unprocessable_entity, :error => e.message }} and return
      end
  ...

它工作得很好,并使它成为底部的东西......

...
format.json { render :json => { :status => :ok, :posts => @res.to_json(:only => [:date, :content, :user_id]) } }
  else
format.json { render :json => { :status => :unprocessable_entity, :error => "must have a _start_ and _end_ date" } }
...

问题是当发生异常并rescue调用该部分时,Rails 不会以 json 响应,而是告诉我“模板缺失”。我的语法有问题吗?

4

2 回答 2

0

Consider this example regarding show action to understand the error

class ModelsController
.
.
  def show
    @model = Model.find(params[:id])

    respond_to do |format|
      format.html
      format.js
    end
  end
end

In this case, if the request is of type html then rails by convention searcher for a file app/views/models/show.html.erb.

But if the request is of type js then rails will search for app/views/models/show.js.erb. If these files does not exist then rails will throw template missing error

so if you are only responding to json then you can do

respond_to do |format|
  format.json do
    begin 
    ..  
    rescue
      render :json => { }
    end 
end
于 2012-06-16T04:47:05.560 回答
0

哦,原来我不需要那个format.json位。为什么呢?

于 2012-06-16T04:01:02.687 回答