Reputation: 582
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
Upvotes: 0
Views: 1057
Reputation: 42863
You should have a validation so the name cannot be nil
validates_presence_of :name
or have a default value so it is always not
change_column :projects, :name, :string, :default => "Sam"
but if you just want it to work you can do this
select('hour','project_id', @projects.collect{|p|["#{p.client.name if !p.client.blank?}", p.id]})
It won't matter if the name is nil because you can call nil but you cannot call nil.attribute
and that is why my solution didn't work the first round.
Upvotes: 1