1

respond_with 实际上是用于 withActiveModel的实例。我尝试将它与OpenStruct's 实例一起使用,但它会引发错误。是否可以将 respond_with 与自定义对象一起使用?

class CryptController < ApplicationController
  respond_to :json

  def my_action
    respond_with OpenStruct.new(foo: 'foo', bar: 'bar')
  end
  # ...
end

引发:**未定义的方法persisted?' for nil:NilClass** ruby-2.1.4@rails4/gems/actionpack-4.2.5.1/lib/action_dispatch/routing/polymorphic_routes.rb:298:inhandle_list' /home/workstat/.rvm/gems/ruby-2.1.4@rails4/gems/actionpack-4.2.5.1/lib/action_dispatch/routing/polymorphic_routes.rb:206:in polymorphic_method' /home/workstat/.rvm/gems/ruby-2.1.4@rails4/gems/actionpack-4.2.5.1/lib/action_dispatch/routing/polymorphic_routes.rb:114:inpolymorphic_url'

4

1 回答 1

0

respond_with是一种将资源公开给 mime 请求的辅助方法。

文档

 respond_with(@user)

对于该create动作,等效于(respond_to :xml在示例中假设):

respond_to do |format|
    if @user.save
      format.html { redirect_to(@user) }
      format.xml { render xml: @user, status: :created, location: @user }
    else
      format.html { render action: "new" }
      format.xml { render xml: @user.errors, status: :unprocessable_entity }
    end
  end
end

精确的等价物取决于控制器的动作。

The key takeaway is that respond_with takes a @instance variable as an argument and first attempts to redirect to the corresponding html view. Failing that, it renders an xml response, in the case above.

You are passing in an ostruct, which doesn't correspond to an instance of your model. In this case, respond_with doesn't know where to redirect to in your views and doesn't have an instance from which to render a mime response.

See this RailsCast and this blogpost from José Valim.

A note: The error undefined method persisted? is generated by Devise and probably because it can't find a route.

于 2016-04-02T19:21:08.453 回答