I am trying to pass stored_products from shopify into a Rails app but keep getting a home controller error at https://f588240c.ngrok.io/ i have made updates, with no luck and restarted the server a number of times with no luck.
Any help would be welcomed. Heres the code
class Api::V1::HomeController < ShopifyApp::AuthenticatedController
def index
@products = ShopifyAPI::Product.find(:all, params: { limit: 10 })
@products.each do |product|
StoredProduct.where(shopify_id: product.id)
.first_or_create do |stored_product|
stored_product.shopify_id = product.id
stored_product.shopify_title = product.title
stored_product.shopify_handle = product.handle
stored_product.shopify_image_url = product.image.src
stored_product.shop_id = @shop.id
stored_product.save
product.images.each do |image|
ProductImage.where(shopify_id: image.id)
.first_or_create do |product_image|
product_image.image_url = image.src
product_image.stored_product_id = stored_product_id
product_image.shopify_id = image.id
end
end
end
end
@stored_products = StoredProduct.belongs_to_shop(@shop.id)
end
end
From the authenticated controller
private
def set_shop
@shop = Shop.find_by(id: session[:shopify])
set_locale
end
from the store_products.rb file
class StoredProduct < ApplicationRecord
belongs_to :shop
has_many :product_images
scope :belongs_to_shop, -> shop_id { where(shop_id: shop_id) }
end
2
Answers
The problem is that
@shop
is nil. The error message says it cannot call the method.id
on NilClass.In the image I can see that you have a shop_id in the params so you might just need to change your code here:
But that depends on your code, so please double check.
For this specific issue/code tutorial, the private set_shop method should be set like follows:
The other answer has
params
instead ofsession