Search code examples
ruby-on-railsbelongs-to

Rails: Is the NoMethodError undefined error linked to belongs_to?


My models are as follows:

    class Project < ApplicationRecord
      belongs_to :workspace
      has_many :tasks, dependent: :destroy
    end

    class Task < ApplicationRecord
      belongs_to :person
      belongs_to :project
    end

    class Person < ApplicationRecord
      belongs_to :company
      has_many :tasks
    end

So as you can see, each task belongs to a project. In addition to this, each task has a person attached to it (who is responsible for the task). In my task model I have a project_id and a person_id.

In my Tasks#Index view I receive a NoMethodError. In the Index view this is what is causing the error:

    <% @task.each do |t| %>
        <tr>
            <td><%= t.person.id %></td>

The exact error is "undefined method `id' for nil:NilClass".

Are my associations incorrect?


Solution

  • It looks to me as if the associations are correct. If they weren't, your error message would have complained about a task having no method called person.

    Instead, the message tells you that t.person is actually nil. I assume that @task is actually some collection of tasks; at least one of them seems to be missing a person.

    If you think every task should definitely have a person, I'd have a look at my data using either the rails console or a GUI for your database. Alternatively, use the safe access operator t&.person&.id which will avoid this error and show you what's happening.