Reputation: 255
I have a join model called AppServer
which references three other models called Environment
, Server
and App
. I also added another field in the AppServer
model called app_server_id
, as I set id => false
for the AppServer
model. I added the app_server_id
field at a later stage, after having populated the table and not getting any further with my other question.
So since I now have app_server_id
, I tried to populate it, using the following method in the AppServer
model:
def generate_id
"#{environment_id}_#{app_id}_#{server_id}"
end
however, in the rails console I wanted to see whether the method works so I done this:
pry(main)> AppServer.first.generate_id
=> "2_3_1"
So now trying either to update the attribute or save it won't work as shown:
pry(main)> AppServer.first.app_server_id = AppServer.first.generate_id
=> "2_3_1"
pry(main)> AppServer.first.app_server_id
=> nil
or
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'
or even
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'
Any idea why that could be?
If you guys need any more code let me know
Upvotes: 1
Views: 205
Reputation: 10564
This
pry(main)> AppServer.first.app_server_id = AppServer.first.generate_id
=> "2_3_1"
pry(main)> AppServer.first.app_server_id
=> nil
doesn't work because you're assigning the app_server_id, not saving it, then referencing the saved version (nil) again.
For this
undefined method `eq' for nil:NilClass
see this question
undefined method `eq' for nil:NilClass with rails 3 and ruby enterprise on ubuntu hardy
Edit
I see no benefit not to auto increment this so I would add an id column using this migration and remove your to_param method:
def self.up
execute "ALTER TABLE 'app_servers'
ADD COLUMN 'id' INT(11) AUTO_INCREMENT NOT NULL FIRST,
ADD PRIMARY KEY('id')"
end
Upvotes: 1