Search code examples
ruby-on-railsrubyruby-on-rails-2

I have somehow broken my Rails app - the dreaded NoMethod Error


The error message is NoMethodError in Circuit#update undefined method 'network_address' for nil:NilClass and related to this line in my view:

<td><%= logical_interface.subnet.network_address %></td>

Everything was working perfectly earlier and now I've managed to break it somehow when I restarted my local server.

update.rhtml

<table id="logical_interfaces">
    <% @logical_interfaces.each do |logical_interface| %>
        <tr id="logical_interface_<%= logical_interface.id %>">
            <td><%= logical_interface.description %></td>
            <td><%= logical_interface.subnet.network_address %></td>
            <td><%= logical_interface.bandwidth %></td>
            </td>
        </tr>
    <% end %>
</table>

logical_interface.rb

belongs_to :subnet
belongs_to :circuit

subnet.rb

belongs_to :logical_interface
belongs_to :circuit

circuit.rb

has_many :subnets
has_many :logical_interfaces

circuit_controller.rb

The CRUD is being done inside the controller of another model because this is the main object which everything else runs off.

def update

  ....
  if params[:id]
    @circuit = Circuit.find(params[:id])
  end

  @logical_interfaces = LogicalInterface.find_all_by_circuit_id(@circuit.id)
  ....

end

As is common with bugs, I'll bet this is something silly but I genuinely can't work it out for myself so would greatly appreciate any answers. I have a feeling it's to do with the relationships that have been defined between the models but I could be wrong.


Solution

  • subnet is nil for logical_interface. Either add some validation in LogicalInterface model:

    validates_presence_of :subnet
    

    or display network_address only if subnet is present.

    <td><%= logical_interface.subnet.try(:network_address) %></td>