【问题标题】:Why is respond_with not returning json from my model?为什么 respond_with 没有从我的模型返回 json?
【发布时间】:2011-08-18 18:44:15
【问题描述】:

在这种情况下,为什么 respond_with 不响应 json?我正在使用显式 .json (/tasks/4e3c1163a19d461203000106/items/4e4c27dfa19d46e0e400000a.json) 调用该操作

在我的控制器中--

class Tasks::TasksController < Tasks::BaseController
  respond_to :html, :js, :json

  def update
    @task = @taskgroup.update_task(params[:id], params[:task])
    @taskgroup.save
    respond_with @task
  end
end

当我覆盖 to_json 并添加断点时,它没有被命中。回应是:

{}

如果我将 respond_with 替换为对 to_json 的显式调用:

respond_with @task do |format|
  format.json { render json: @task.to_json }
end

回复完美:

{
"_id":"4e4c27dfa19d46e0e400000a",
"assigned_to":null,
"comments"  [{"_id":"4e4c2fd7a19d46e127000014", 
[SNIP]

在后一种情况下它工作正常,但我想弄清楚为什么第一个不起作用。这发生在我的应用程序中的其他控制器和模型上。不知道它是不是一个类的东西? (rails 3.0.9 / mongoid 2.1.8)

【问题讨论】:

  • 你能告诉我如果你重新订购respond_to :json, :html, :js 会继续这种行为吗?
  • @Gerry 重新排序并没有帮助。
  • 好吧,看看情况如何。当您在update 操作中调用respond_with 时(如果对象有效),它将重定向到show 操作(如果您不想要此默认行为,则必须将location: "other_action" 提供给respond_with)。您能提供您的show 操作吗?
  • @Gerry -- 啊,对。如果存在验证错误,它可以正常工作。由于我只想返回 json 而不进行重定向,因此我将坚持使用更详细的自定义块。继续添加您的评论作为答案。
  • 很高兴我在某种程度上帮助了你:)!

标签: ruby-on-rails-3 mongoid


【解决方案1】:

这是我写的一个猴子补丁,它总是用你告诉它做的事情来响应,而不管协议如何。 请注意,这确实会破坏 RESTful 最佳实践,如果您以 RESTful 方式做出响应,那么它可能会破坏。但是,如果您的 JSON/XML 响应与主应用程序分开,那么它很有用,并且您的其他控制器将不破。

用法,将其包含在任何控制器中以覆盖 respond_with 功能。

class ApiController < BaseController
  include ValidResponder
end

那么任何扩展 ApiController 的东西都会包含这个功能。

将以下内容保存在 app/lib/valid_responder.rb 中:

#Override restful responses.
module ValidResponder
  def self.included(base)
    ActionController::Responder.class_eval do
      alias :old_api_behavior :api_behavior
      define_method :api_behavior do |error|
        if controller.class.ancestors.include?(base)
          raise error unless resourceful?
          display resource
        else
          old_api_behaviour(error)
        end
      end
    end
  end
end

供参考,实际方法来源在这里:http://api.rubyonrails.org/classes/ActionController/Responder.html#method-i-api_behavior

【讨论】:

    【解决方案2】:

    好的,看看情况如何。当您在update 操作中调用respond_with 时(如果对象有效),它将重定向到show 操作(如果您不希望这种默认行为,您必须将location: "other_action" 提供给respond_with)。

    【讨论】:

    • 格里,谢谢你的回答,但可以更明确一点吗?如果我想在更新方法中使用respond_with 并且实际上让它返回json,我应该将location 设置为什么?
    猜你喜欢
    • 2017-02-09
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 2016-11-11
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多