2011-08-23 73 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