views:

52

answers:

1

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

+1  A: 

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.

Sam
The client id is not a must field so i have some projects with client and some projects without a client. because of that i cannot use the validates_presence_of :name solution. I copied and past your third solution <%=select('hour','project_id', @projects.collect{|p|["#{p.client.name if !p.client.name.blank?}", p.id]})%> but i still get the error: undefined method `name' for nil:NilClass
winter sun
Oh, that's because the nil object is the client, not the name. I updated the code
Sam
ThanksGreat!! It is working now after the correctionThanks very much
winter sun