开发者

ruby on rails select form helper Null values validation

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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜