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
self.primary_key = "id"and just use RailsApi defaults. Also add a presence check if a product might nog have a shop (if it should always have a shop a presence check is redundant) - Peter de Ridder