ActionView::Template:Error(undefined method 'first_name' for nil:NilClass)

白昼怎懂夜的黑 提交于 2020-01-07 00:36:42

问题


My app seems to randomly be throwing an error when users are trying to load grid data into the form:

   ActionView::Template::Error (undefined method `first_name' for nil:NilClass):
3:          t = @conts
4:                          xml.tag!("row",{ "id" => t.id }) do
5:
6:                                  xml.tag!("cell", t.first_name)
7:                                  xml.tag!("cell", t.last_name)
8:                          xml.tag!("cell", t.email)
9:                                  xml.tag!("cell", t.phone_1)

And following is the controller file

 def compdata
       @conts = Continfo.find_by_id(params[:id])
    end

Correspondence compdata RXML file

     xml.instruct! :xml, :version=>"1.0" 
       xml.tag!("rows") do
     t = @conts
        xml.tag!("row",{ "id" => t.id }) do

            xml.tag!("cell", t.first_name)
            xml.tag!("cell", t.last_name)
            xml.tag!("cell", t.email)
            xml.tag!("cell", t.phone_1)
            xml.tag!("cell", t.phone_2)
            xml.tag!("cell", t.homepage)
            xml.tag!("cell", t.skype)
    end
end

回答1:


First item

It looks like you have a few other similar questions (here and here) open right now, and for both the current one and this one it looks like your @conts value is currently nil meaning nothing was brought back when it ran the search:

def compdata
  @conts = Continfo.find_by_id(params[:id])
end

Are you sure there is a value available in your table with the id equal to params[:id]?

If there is a mismatch there, that would be the first place I would look.

Second item

You may also run into an issue trying to call the method each on @conts because the find_by_id method will not bring back an array. If you want it to iterate over each record instead of each key/val, try using find_all_by_id which will return an array.

Third item

After looking at your other question, it looks like your syntax on this is different, but shouldn't you iterate over @conts again like this?

xml.tag!("rows") do
  @conts.each do |t|
    xml.tag!("row",{ "id" => t.id }) do
      xml.tag!("cell", t.first_name)
      xml.tag!("cell", t.last_name)
      xml.tag!("cell", t.email)
      xml.tag!("cell", t.phone_1)
      xml.tag!("cell", t.phone_2)
      xml.tag!("cell", t.homepage)
      xml.tag!("cell", t.skype)
    end
  end
end

This would be the way to assign t instead of like t = @conts, especially if you plan to step through many of them.



来源:https://stackoverflow.com/questions/8722629/actionviewtemplateerrorundefined-method-first-name-for-nilnilclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!