未定义的方法“model_name”在轨道 3 中
为对象渲染 xml 时,出现错误
NoMethodError(OrderResponse:Class 的未定义方法“model_name”):
OrderResponse.rb
class OrderResponse
include ActiveModel::Serialization
attr_accessor :payload
end
在控制器中,
def create
@order_response = OrderResponse.new
@order_response.payload = 12345
respond_to do |format|
format.xml { render :xml => @order_response }
end
end
我在搜索时发现了具有类似标题的其他问题,根据我用“respond_with”修改了“respond_to”,这又引发了错误
OrderResponse 中未定义的方法“model_name”
如何解决这个问题?
While rendering xml for an object, I am getting the error
NoMethodError (undefined method `model_name' for OrderResponse:Class):
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
undefinedMethod 'model_name' in OrderResponse
How to solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我在 stackoverflow 上的某个地方找到了这个问题的答案,希望我能相信来源......这是我对它的解释。
在 Rails 3 中,如果您的路由中列出了一个资源,该资源具有模型 .rb 文件,但其后面没有活动记录表,那么您将看到此类错误。对我来说,这似乎是一个 form_for 试图引用此模型中的 :controller 和 :action 。也许它与 Rails 尝试处理模型的关联或类似的东西有关。不管怎样,这对我来说是新的,因为我从 Rails 2.3.8 升级了应用程序。
对我来说,显示为:
要修复它,请在受影响的类的顶部添加:
这对我来说在两个这样的模型上都有效。
I found an answer to this somewhere on stackoverflow and wish I could credit the source... This is my interpretation of it.
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. This appeared for me as a form_for trying to reference a :controller and :action in this model. Perhaps it is related to Rails attempting to process associations for the model or something similar. Either way, this is new for me since I upgraded an application from Rails 2.3.8.
For me, the appears as:
To fix it, at the top of the affected class add:
This has worked for me on two models like this.
您可以尝试按该名称定义一个类方法,该方法返回类的名称:
You could try defining a class method by that name, which returns the name of the class:
尝试包含定义 model_name 的
ActiveSupport::CoreExtensions::Module
ActiveSupport ::核心扩展::模块try including
ActiveSupport::CoreExtensions::Module
where model_name is defined ActiveSupport::CoreExtensions::Module