I have a client table (with fields id, name) and a project table (with fields id, name, client_id).
My project model is:
class Project < ActiveRecord::Base
belongs_to :client
end
I need to display in one selection list the client name and the project name.
In the following code everything is working well, and I get in the selection list the client name concatenated with the project name (for example: IBM PROJECT_DEMO)
select('hour','project_id',
@projects.collect{ |project|
[project.client.name+project.name,project.id]})
The problem begin when I have a project without a client in this case I get the error
undefined method `name' for nil:NilClass
I tried to insert an if statement in order to check the client name existence
like this
select('hour','project_id',
@projects.collect{ |project|
[project.client.name if project.client+project.name,project.id]},
{:prompt => 'Select Project'})
but it not working and I get an error
I will be most appreciate if someone could give me some solution to this problem
Thanks
You should have a validation so the name cannot be nil
or have a default value so it is always not
but if you just want it to work you can do this
It won’t matter if the name is nil because you can call nil but you cannot call
nil.attributeand that is why my solution didn’t work the first round.