简体   繁体   中英

Rails Associations - undefined method for nil:NilClass

Basic question on Rails associations with the following tables:

  • Shop: name, network
  • Product: title, price, shop_id

Relation defined as has_many and belongs_to :

Model:

shop.rb

class Shop < ApplicationRecord
    has_many   :products
end

product.rb

class Product < ApplicationRecord
     self.primary_key = "id"
     belongs_to :shop
end

Controller:

shops_controller.rb

  def show
    @shop = Shop.find(params[:id])
 end

products_controller.rb

  def show
    @product = Product.find(params[:id])
  end

In the Shop view I manage to reference and show all Products for each Shop without problems:

<%= @shop.name %>
<%= @shop.network %>

  <% @shop.products.each do |product| %>
   <%= product.title %>
  <% end %>

But the other way around in the Product view I don't manage to show the network information from the Shop table :

  <%= @product.title %>
  <%= @product.shop.network %>

This returns the following error:

undefined method `network' for nil:NilClass

As user jith pointed out - the setup is correct and working. The problem was that one specific shop_id could not be found.

So make sure all _id's are in the other table when working with associations.

Thank you!

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-2024 STACKOOM.COM