Load Vendor Object By Name Parameter Extracted Fro

2019-08-22 04:28发布

问题:

I'm trying to create a route that link to the store page of each Vendor using Spree Commerce. The page should list the details (name, about us, etc), and the products of the given vendor.

https://example.com/stores/vendor-one

My routes.rb configuration :

Spree::Core::Engine.routes.draw do
    resources :stores
end

My stores_controller controller :

module Spree
    class StoresController < Spree::StoreController  
      require 'vendor'
      def show
        @vendor = current_spree_vendor
      end     
    end
end

My show.html.erb template :

<h2><%= @vendor.name %></h2>
<p><%= @vendor.about_us %></p>

The error that I'm getting :

NoMethodError in Spree::Stores#single

Showing /myapp/app/views/spree/stores/show.html.erb where line #2 raised:

undefined method `name' for nil:NilClass

Line # 2 : <h2><%= @vendor.name %></h2>

How can I load the given Vendor by getting its name from the url ? I'm new to Rails so any help will be highly appreciated !

回答1:

The way to debug errors like this is by working backwards from the error. The error is occurring in the template because @vendor is nil. Why? The controller has a #show method that is setting @vendor, but it is setting @vendor to the result of current_spree_vendor, so it must be that current_spree_vendor returned nil. So now you need to examine current_spree_vendor and figure out why it is sometimes returning nil.

You will soon learn how to debug this sort of error, and you'll need to because these kinds of errors are too common, and too specific, to be something that the internet can help you with. Even when the internet can help, it's too slow and waiting for answers on it will keep you from getting the job done.