Ruby on rails 无法初始化ActiveRecord对象
我正在尝试在rails控制台中执行此操作Ruby on rails 无法初始化ActiveRecord对象,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,我正在尝试在rails控制台中执行此操作 >> user = User.new(:name => "", :email => "test@example.com") => #<User not initialized> >user=user.new(:name=>“”,:email=>”test@example.com") => # 我的用户类看起来像 class User < ActiveRecord::Base attr_accesso
>> user = User.new(:name => "", :email => "test@example.com")
=> #<User not initialized>
>user=user.new(:name=>“”,:email=>”test@example.com")
=> #
我的用户类看起来像
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
class用户
我从后面跟着。为什么我不能初始化对象 您是否在与项目相同的文件目录中运行控制台?我还尝试将符号转换为书中使用的示例,看看这是否有帮助 您也可以尝试在没有属性的情况下调用User.new,查看它是否生成本教程6.1.3中列出的对象,然后填写属性并查看它是否有效 还要确保在模型中没有对用户名进行验证
最后一项检查是,您可以运行user.error查看为什么它可能没有保存您是否正在运行console,使用
rails c
命令从项目的根目录加载您的环境?键入irb
启动控制台会话本身不会加载Rails应用程序环境
下面是一些更多的故障排除提示
- 检查以确保
中指定的开发数据库正在运行config/database.yml
- 检查以确保存在迁移以创建Users表
- 检查以确保迁移已使用
rake db:migrate运行
- 检查以确保数据库中确实存在用户表,字段:name和:email的列类型为
(或varchar
)text
用户
模型在Rails应用程序中仍然存在。这意味着,在运行rails控制台之前,您已经有了一个迁移的用户
模型
如果该表不存在,系统将立即提示您:
=>用户(表不存在)
现在,让我们在rails控制台中享受一下乐趣:
首先,不要覆盖Rails模型中的initialize
方法;虽然从ActiveRecord创建对象初始化方法优先(我认为),但它可能会产生冲突。相反,在初始化回调后使用。在控制台中:
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
tl;dr:完全照抄这本书,你会没事的。(注:我是作者。)
所讨论的示例来自,不是活动记录模型。特别是,问题中显示的用户类基于:
类用户
属性访问器:名称,:电子邮件
def初始化(属性={})
@名称=属性[:名称]
@电子邮件=属性[:电子邮件]
结束
def格式化电子邮件
“#{@name}”
结束
结束
此类不继承自ActiveRecord::Base
,而是必须使用require./example\u user.rb'
显式包含在控制台中,如中所述。您看到的行为是将
包含在第一行中的结果,但是如果您将代码完全复制,您应该会看到预期的行为。根据您的教程,他们要求您使用name:,email:
而不是:name=>,:email=>“
这可能是你的问题吗?我想这可能是问题所在。但我两种风格都试过了,都没有成功。试过你的建议。目前没有运气:-(根据您的要点,这里有一个要点,我修改了上面的答案。它肯定会帮助您解决问题。尝试了您所有的故障排除技巧。仍然没有结果。这是一个相当多的3管道问题。谢谢您的回答。我实际上在看第6章,而不是第4章。清单6.2显示用户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>"
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