Ruby:Class.new 给出“未初始化的类";Rails 控制台中的错误 [英] Ruby: Class.new gives "Class not initialized" error in rails console

查看:46
本文介绍了Ruby:Class.new 给出“未初始化的类";Rails 控制台中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个轻量级应用程序来创建和显示即将发生的事件的信息.我定义了一个 Event 类,它采用 args 哈希作为参数.初始化方法定义如下.

I'm creating a lightweight app to create and display information for upcoming events. I have an Event class defined that takes an args hash as a parameter. The initialize method is defined below.

class Event < ActiveRecord::Base

  def initialize(args={})
    @what       = args[:what]
    @theme      = args[:theme]
    ... 
  end
end

到目前为止,一切都很好.然后,在 Rails 控制台中,我定义了一个 args 哈希并尝试创建一个 Event 实例,但出现以下错误.

So far, so good. Then, in Rails Console, I define an args hash and try to create an instance of Event but get the following error.

[4] pry(main)> args = {what: 'what', theme: 'theme'}
=> {:what=>"what", :theme=>"theme"}
[5] pry(main)> Event.new(args)
=> #<Event not initialized>

这看起来很简单,但我很难弄清楚.任何帮助表示赞赏.

This seems really straightforward but I'm having trouble figuring it out. Any help is appreciated.

推荐答案

如果你想为继承 ActiveRecord 的类做一个 def initialize 块,你必须调用 super(args) 在此块中,以便正确初始化子类.

If you want to do a def initialize block for ActiveRecord-inheriting classes, you have to call super(args) inside this block in order for the subclass to be properly initialised.

但是,如果 whattheme 已经作为列存在于您的模型中,则不需要 initialize 方法:Event.new(args) 开箱即用.

However, if what and theme already exists as columns in your model, you don't need the initialize method: Event.new(args) will work fine out of the box.

一个好的做法是仅在需要定义 ActiveRecord 模式中不存在的变量(例如设置不需要持久性的实例变量)时才使用 initialize 块,但如果需要要做到这一点,那么使用 attr_accessor 是更常见的做法.

A good practice would be to only use initialize block when you need to define variables that are not present in your ActiveRecord schema (e.g. setting instance variables that do not need persistence), but if you need to do that then it's the more common practice to use attr_accessor.

这篇关于Ruby:Class.new 给出“未初始化的类";Rails 控制台中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆