【问题标题】:Rails: respond_with custom objectRails:respond_with 自定义对象
【发布时间】:2016-04-02 17:23:18
【问题描述】:

respond_with 实际上是用于ActiveModel 的实例。我尝试将它与OpenStruct 的实例一起使用,但它会引发错误。 是否可以将 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'

【问题讨论】:

  • 你能先显示你的代码和错误吗? respond_with 也适用于 AR 对象。
  • @ArupRakshit 我已经更新了问题

标签: ruby-on-rails ruby responders


【解决方案1】:

respond_with 是一种帮助方法,可将资源公开给 mime 请求。

来自documentation

 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

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

关键点是respond_with 将@instance 变量作为参数并首先尝试重定向到相应的html 视图。否则,它会在上述情况下呈现一个 xml 响应。

您正在传递一个 ostruct,它与您的模型实例不对应。在这种情况下,respond_with 不知道在您的视图中重定向到哪里,也没有可以从中呈现 mime 响应的实例。

查看来自 José Valim 的 RailsCastthis blogpost

注意:错误undefined method persisted? 是由Devise 生成的,可能是因为它找不到路由。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-08
    • 2011-04-14
    • 1970-01-01
    • 2023-04-02
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多