Reputation: 81
Basic question on Rails associations with the following tables:
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
Upvotes: 0
Views: 2437
Reputation: 81
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!
Upvotes: 1