简体   繁体   English

Rails 3中未定义的方法“ model_name”

[英]undefined method `model_name' in rails 3

While rendering xml for an object, I am getting the error 呈现对象的xml时,出现错误

NoMethodError (undefined method `model_name' for OrderResponse:Class): NoMethodError(OrderResponse:Class的未定义方法“ model_name”):

OrderResponse.rb OrderResponse.rb

class OrderResponse
   include ActiveModel::Serialization

   attr_accessor :payload
end

In controller 在控制器中

def create
  @order_response = OrderResponse.new
  @order_response.payload = 12345

  respond_to do |format|
    format.xml { render :xml => @order_response }
  end
end

I found other questions with similar titles while searching, according to that i modified 'respond_to' with 'respond_with' which inturns throws an error 我在搜索时发现了其他标题相似的问题,因为我用“ respond_with”修改了“ respond_to”,这反过来引发了错误

undefinedMethod 'model_name' in OrderResponse OrderResponse中的undefinedMethod'model_name'

How to solve this? 如何解决呢?

I found an answer to this somewhere on stackoverflow and wish I could credit the source... This is my interpretation of it. 我在stackoverflow上的某个地方找到了答案,希望我能相信它的源……这是我对它的解释。

In Rails 3, if you have a resource listed in your routes which has a model .rb file but no active record table behind it, then you'll see this kind of error. 在Rails 3中,如果您的路由中列出了一个资源,该资源中有一个.rb文件模型,但后面没有活动记录表,那么您将看到这种错误。 This appeared for me as a form_for trying to reference a :controller and :action in this model. 对于我来说,这似乎是一个form_for,试图在此模型中引用:controller和:action。 Perhaps it is related to Rails attempting to process associations for the model or something similar. 可能与Rails试图处理模型或类似物的关联有关。 Either way, this is new for me since I upgraded an application from Rails 2.3.8. 无论哪种方式,这对我来说都是新的,因为我是从Rails 2.3.8升级了一个应用程序。

For me, the appears as: 对我来说,显示为:

undefined method `model_name' for SomeModel:Class SomeModel:Class的未定义方法“ model_name”

To fix it, at the top of the affected class add: 要解决此问题,请在受影响的类的顶部添加:

extend ActiveModel::Naming
include ActiveModel::Conversion
def persisted?
  false
end

This has worked for me on two models like this. 这对我这样的两个模型有用。

您可以尝试使用该名称定义一个类方法,该方法返回该类的名称:

def self.model_name; 'OrderResponse'; end

尝试包括ActiveSupport::CoreExtensions::Module ,其中模型名称被定义的ActiveSupport :: CoreExtensions ::模块

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM