无法初始化ActiveRecord对象

时间:2013-06-04 17:48:33

标签: ruby-on-rails ruby activerecord

我正在尝试在rails控制台中进行操作

>> user = User.new(:name => "", :email => "test@example.com")
=> #<User not initialized>

我的用户类看起来像

class User < ActiveRecord::Base
  attr_accessor :name, :email
  has_many :microposts

  def initialize(attributes = {})
    @name  = attributes[:name]
    @email = attributes[:email]
  end 

  def formatted_email
    "#{@name} <#{@email}>"
  end
end

我跟随rails tutorial。为什么我无法初始化对象?

4 个答案:

答案 0 :(得分:4)

tl; dr :完全从书中复制,你应该没问题。 (注意:我是作者。)

相关示例来自Chapter 4Ruby on Rails Tutorial book是Active Record模型。特别是,问题中显示的用户类基于Listing 4.9

class User
  attr_accessor :name, :email

  def initialize(attributes = {})
    @name  = attributes[:name]
    @email = attributes[:email]
  end

  def formatted_email
    "#{@name} <#{@email}>"
  end
end

此类继承自ActiveRecord::Base,而是必须使用require './example_user.rb'在控制台中明确包含,如Section 4.4.5中所述。您看到的行为是在第一行中包含< ActiveRecord::Base的结果,但如果您在Listing 4.9中复制代码,则应该看到预期的行为。

答案 1 :(得分:2)

您是否在与项目相同的文件目录中运行控制台?我也尝试将符号转换为书中使用的示例,看看是否能让你随处可见。

您也可以尝试调用没有属性的User.new,看看它是否生成了教程6.1.3中列出的对象,然后填写属性并查看它是否有效。

还要确保您的模型中没有对您的用户名进行验证。

并且最后一次检查你可以运行user.error来查看它可能没有保存的原因

答案 2 :(得分:2)

首先,我假设您的Rails应用程序中存在User模型。这意味着,在运行User之前,您已经拥有已迁移的rails console 模型。
如果该表不存在,将立即通过以下方式提示您:

  

=&GT;用户(表不存在)

现在,让我们在rails console中有一些乐趣:
首先,不要在Rails模型中覆盖initialize方法;虽然从ActiveRecord创建对象初始化方法优先(我认为),但它可能会产生冲突。而是使用after_initialize回调。在控制台中:

class User < ActiveRecord::Base
  attr_accessible :name, :email

  def after_initialize(attributes = {})
    self[:name]  = attributes[:name]
    self[:email] = attributes[:email]
  end
  def formatted_email
    "#{self.name} <#{self.email}>"
  end
end

现在,

u = User.new({name: "Foo", email: "foo@bar.org"})
#<User name: "Foo", email: "foo@bar.org", created_at:nil updated_at: nil>
u.formatted_email
#=> "Foo <foo@bar.org>"

全部完成!甜。

<强>更新
根据您最近的gist;我认为根本没有after_initialize。 Rails就是这样做的。
首先,将attr_accessor替换为attr_accessbile attr_accessor是ruby方法(礼貌,元编程),它为提供的实例变量创建getter和setter。 Rails使用attr_accessible;出于安全考虑,只允许attr_accessible中允许的实例变量进行批量分配(通过发送params散列)。

user.rb

class User < ActiveRecord::Base
  attr_accessible :name, :email

  #def after_initialize(attributes = {})
  #  self[:name]  = attributes[:name]
  #  self[:email] = attributes[:email]
  #end 

  def formatted_email
    "#{self.name} <#{self.email}>"
  end
end

答案 3 :(得分:0)

您是否使用rails c命令运行控制台以从项目的根目录加载环境?键入irb以启动控制台会话不会单独加载Rails应用程序环境。

以下是一些疑难解答提示

  • 检查以确保config/database.yml中指定的开发数据库正在运行
  • 检查以确保存在迁移以创建“用户”表
  • 检查以确保迁移已与rake db:migrate
  • 一起运行
  • 检查以确保数据库中确实存在Users表,其中包含类型为varchar(或text)的列:name和:email
相关问题