2011-08-23 71 views
1

属性我有一个名为AppServer联接模型,它引用了其他三款车型称为EnvironmentServerApp。我还在AppServer模型中添加了另一个字段app_server_id,因为我为AppServer模型设置了id => false。我在稍后的阶段添加了app_server_id字段,之后填入表格并且没有进一步与我的other question更新/保存在连接模型

那么既然我现在有app_server_id,我试图填充它,使用下面的方法在AppServer模式:

def generate_id 
    "#{environment_id}_#{app_id}_#{server_id}" 
end 

然而,在轨控制台我想看看该方法是否有效,所以我做了这样的:

pry(main)> AppServer.first.generate_id 
=> "2_3_1" 

所以现在想要么更新的属性或保存它不会工作,如下所示:

pry(main)> AppServer.first.app_server_id = AppServer.first.generate_id 
=> "2_3_1" 
pry(main)> AppServer.first.app_server_id 
=> nil 

pry(main)> AppServer.first.update_attribute(:app_server_id, AppServer.first.generate_id) 
NoMethodError: undefined method `eq' for nil:NilClass 
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.9/lib/active_support/whiny_nil.rb:48:in `method_missing' 

甚至

pry(main)> apps=AppServer.first 
=> #<AppServer app_id: 3, server_id: 1, environment_id: 2, app_server_id: nil> 
pry(main)> apps.app_server_id = apps.generate_id 
=> "2_3_1" 
pry(main)> apps.save 
NoMethodError: undefined method `eq' for nil:NilClass 
from C:/Ruby192/lib/ruby/gems/1.9.1/gems/activesupport-3.0.9/lib/active_support/whiny_nil.rb:48:in `method_missing' 

任何想法,为什么会这样?

如果你们需要更多的代码,让我知道

+0

为什么您的IRB提示会说'撬'? – horseyguy

+0

@banister那是因为我使用不同的REPL而不是IRB。检查一下[关于RailsCast](http://railscasts.com/episodes/280-pry-with-rails?autoplay=true) – omarArroum

+0

是不是很好?你到目前为止对于新的REPL有什么看法? – horseyguy

回答

1

pry(main)> AppServer.first.app_server_id = AppServer.first.generate_id 
=> "2_3_1" 
pry(main)> AppServer.first.app_server_id 
=> nil 

因为你分配app_server_id,不保存它,然后引用保存的版本(无)不工作再次。

对于这个

undefined method `eq' for nil:NilClass 

看到这个问题

undefined method `eq' for nil:NilClass with rails 3 and ruby enterprise on ubuntu hardy

编辑

我看不出有什么好处没有自动增量这个,所以我会用这种迁移添加ID列,删除你的to_param方法:

def self.up 
    execute "ALTER TABLE 'app_servers' 
       ADD COLUMN 'id' INT(11) AUTO_INCREMENT NOT NULL FIRST, 
       ADD PRIMARY KEY('id')" 
end 

Credit where due

+0

丰富多了,但在我的代码中,我还使用了另一种方法,我称之为“save”方法,但即使这样也不起作用 – omarArroum

+0

save和update_attribute都导致了我链接的错误到另一个相关的问题。我的建议是在连接表中添加一个id列。 – mark

+0

这是我试图做的。我创建了'app_server_id',它应该是我的表格ID,所以我可以访问它。我究竟做错了什么? – omarArroum