0
votes

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
1
Every product belongs to a shop, or are there somevwithout? - Ruby Racer
All products have one shop (referenced in the product table with shop_id) - Karsten
have you checked whether shop_id is right and not null? - jithya
Thank you, sometimes the solution is so simple. That specific shop_id I tested was not in the shop table. So setup in general is correct. Thanks again, this took me a long time! - Karsten
Unrelated to the already answered question: I would remove 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

1 Answers

1
votes

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!