ruby-on-rails - Rails respond_with 输出 json 并尝试将其作为方法调用

标签 ruby-on-rails ruby rest ruby-on-rails-3

我创建了一个用 json 响应的简单 api。当我尝试从浏览器调用它时,我得到了适当的 json 响应,但是当我尝试从 actionscript 远程调用它时,它似乎试图调用 json,就好像它是一个方法一样。这是 Controller 操作:

  def matcher
    @conn = Connection.first
    if(@conn)
      respond_with({:conn => @conn, :status => :ok}.to_json)
    else
      respond_with({:status => :no_content}.to_json)
    end
  end

这是服务器收到调用时的响应

Started POST "/connection/matcher/1.json" for 127.0.0.1 at 2010-11-11 22:57:24 -0800
  Processing by ConnectionsController#matcher as JSON
  Parameters: {"stratus_string"=>"bad1de003755eaa01a2920f0091d0dd66beaf2d34f651b09a578afb1b54e5686", "user_id"=>"1", "id"=>"1"}
  Connection Load (0.5ms)  SELECT "connections".* FROM "connections" LIMIT 1
Completed   in 24ms

NoMethodError (undefined method `{"conn":{"created_at":"2010-11-12T06:55:13Z","id":6,"stratus_string":"474735730abe81d7622d377bd0bf816c3f94721ece3eddf670bf3a74b1c2356c","updated_at":"2010-11-12T06:55:13Z","user_id":1},"status":"ok"}_url' for #<ConnectionsController:0x000001030e4350>):
  app/controllers/connections_controller.rb:7:in `matcher'

为什么 Rails 试图执行 json 响应?我不明白。

更新:

这是进行调用的 actionscript 代码,但我不明白为什么它会产生影响。

        this.restService = new HTTPService();
        this.restService.url = "http://localhost:3000/connection/matcher/1.json";
        this.restService.method = "POST";

        this.restService.addEventListener("result", onRestResult);
        this.restService.addEventListener("fault", onRestFault);

        var request:Object = new Object();
        request.user_id = user;
        request.stratus_string = id;
        this.restService.cancel();
        this.restService.send(request);

谢谢!

最佳答案

我很好奇为什么它可以在浏览器中运行。我希望它也在那里失败。 检查 respond_with 的来源:

def respond_with(*resources, &block)
  raise "In order to use respond_with, first you need to declare the formats your " <<
        "controller responds to in the class level" if self.class.mimes_for_respond_to.empty?

  if response = retrieve_response_from_mimes(&block)
    options = resources.extract_options!
    options.merge!(:default_response => response)
    (options.delete(:responder) || self.class.responder).call(self, resources, options)
  end
end

很明显为什么它试图将它用作一种方法。 我猜你被困在了:

respond_to do |format|
  format.html # some.html.erb
  format.json  { render :json => {:conn => @conn, :status => :ok}.to_json }
end

关于ruby-on-rails - Rails respond_with 输出 json 并尝试将其作为方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4162318/

相关文章:

ruby-on-rails - 在 Rails 6 中指定命名空间之外的 Controller

ruby-on-rails - 如何以当前用户或非用户身份更新资源?

JavaScript:未捕获语法错误:参数列表后缺少 )

rest - 如何从delphi中的代码将poDoNotEncode添加为TRUE

javascript - ASP.NET REST POST - JavaScript (jQuery) 在 POST 中发送正文

java - 如何将改造 JSON 响应转换为列表?

ruby-on-rails - 从两个 id 创建 rails 记录

ruby-on-rails - Rails 应用程序之间的通信

ruby-on-rails - MongoDB 不断查询命名空间

ruby-on-rails - PG::InsufficientPrivilege: 错误:必须是数据库的所有者