简体   繁体   中英

Rails: undefined method `id' for nil:NilClass

I am rendering form like that:

= f.fields_for :files do |files_form|
  = render('file_form', f: files_form)

In the _file_form.html.slim I have such a code:

- id = f.object.id
- file= f.object.files.first

li.panel.panel-default
  .panel-heading role="tab" id="heading"
    a.file-heading data-toggle="collapse" data-parent="#files" href="#collapse#{id}"
      div.clearfix role="button"
        span = f.object.name
  .panel-collapse.collapse-in id="collapse#{id}" role="tabpanel"
    .panel-body
      .clearfix = link_to(t('shared.destroy'), '#', class:'btn btn-warning btn-sm discard-file pull-right')
      .form-group
        = f.label(:name, t('activerecord.attributes.file.name'))
        = f.text_field(:name, class: 'form-control')
        = f.label(file.id) //my problem

everything works fine until I try to get label with the file id.

Error message: undefined method `id' for nil:NilClass

It looks like is not initialized but actually, when I check it in debugger before line with file.id , it is initialized and I can easily check it value.

When I'm using :id instead of file.id , everything work fine. Why?

Why file is nil class when i trying to retrieve id (or any other data) from it?

Your files collection is empty. Therefore when you do file = f.object.files.first , the file local variable gets assigned nil .

When you try to access it as an object having an attribute with the name id it expectedly throws.

Depending on your use case you can either bail if there are no elements in collection or use a technique to handle nil value:

f.label(file.try(:id))

or

f.label(file&.id) # Ruby 2.3.0 and up

or

f.label(file.id rescue 'placeholder label')

UPDATE

For fields_for to work, the parent model needs to accept the attributes for its associated objects that you use. Make sure you have this in your parent model:

has_many :files
accepts_nested_attributes_for :files

Unless the latter line is there, the form object will be nil, which may be the reason for the behaviour you're observing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM