如果rails中的控制器中有if语句,我在哪里放置respond_to?

时间:2010-06-10 04:49:02

标签: ruby-on-rails json respond-to

我有一个具有if条件的控制器:

  def update
    @contact_email = ContactEmail.find(params[:id])

    if @contact_email.update_attributes(params[:contact_email])
      flash[:notice] = "Successfully updated contact email."
      redirect_to @contact_email
    else
      render :action => 'edit'
    end
  end

我在哪里放置respond_to块:

respond_to do |format| 
  format.html {}
  format.json {render :json =>@contact_email}
end

1 个答案:

答案 0 :(得分:7)

def update
  @contact_email = ContactEmail.find(params[:id])
  ok = @contact_email.update_attributes(params[:contact_email])

  respond_to do |format| 
    format.html {
      if ok
        flash[:notice] = "Successfully updated contact email."
        redirect_to @contact_email
      else
        render :action => 'edit'
      end
    }
    format.json {
      if ok
        render :json =>@contact_email
      else
        ...
      end
    }
  end
end