從我ItemsController
訪問@favorites = current_viewer.favorites_items.where(item_id: @item.id)
當我收到一個錯誤:的Rails:NoMethodError在上述ItemsController#顯示
NoMethodError in ItemsController#show
undefined method `favorites_items' for nil:NilClass
items_controller.rb
def show
@favorites = current_viewer.favorites_items.where(item_id: @item.id)
@comments = Comment.where(item_id: @item).order("created_at DESC")
@items = Item.find(params[:id])
end
型號協會:
class Viewer < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :comments, dependent: :destroy
has_many :favorites
has_many :favorite_items, through: :favorites, source: :favorited, source_type: 'Item'
end
class Favorite < ApplicationRecord
belongs_to :viewer
belongs_to :favorited, polymorphic: true
end
class Item < ApplicationRecord
belongs_to :seller
belongs_to :category
has_many :comments, dependent: :destroy
mount_uploaders :attachments, ImageUploader
end
路線.rb
devise_for :viewers, controllers: {registrations: 'viewers/registrations', sessions: 'viewers/sessions'}
devise_scope :viewer do
get "viewers/index"=> "viewers/sessions#index", :as => "viewer_index"
end
get '/favorites', to: 'favorite_items#index', as: 'favorites'
resources :favorite_items, only: [:create, :destroy]
更新1
我byebug輸入下一三次:
40:
41: # GET /items/1
42: # GET /items/1.json
43: def show
44: byebug
=> 45: @favorites = current_viewer.favorites_items.where(item_id: @item.id)
46: @comments = Comment.where(item_id: @item).order("created_at DESC")
(byebug)
in /.rvm/gems/ruby-2.4.0/gems/actionpack-5.1.4/lib/action_controller/metal/rescue.rb
17:
18: private
19: def process_action(*args)
20: super
21: rescue Exception => exception
=> 22: request.env["action_dispatch.show_detailed_exceptions"] ||= show_detailed_exceptions?
23: rescue_with_handler(exception) || raise
24: end
25: end
26: end
(byebug)
18: private
19: def process_action(*args)
20: super
21: rescue Exception => exception
22: request.env["action_dispatch.show_detailed_exceptions"] ||= show_detailed_exceptions?
=> 23: rescue_with_handler(exception) || raise
24: end
25: end
26: end
(byebug)
您沒有定義'current_viewer'。 – coreyward
因爲你正在使用設計你應該使用current_viewer –
@ Gabriel Mesquita ...它只是一個錯字,現在我改了它 – Theopap