从我的@favorites = current_viewer.favorites_items.where(item_id: @item.id)
访问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
的routes.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)
答案 0 :(得分:3)
由于您拥有不同类型的用户角色,因此您需要正确访问您的帮助程序:
def show
if current_viewer
@favorites = current_viewer.favorites_items.where(item_id: @item.id)
elsif
@favorites = current_seller.favorites_items.where(item_id: @item.id)
end
@comments = Comment.where(item_id: @item).order("created_at DESC")
@items = Item.find(params[:id])
end
current_viewer助手为零,因为您是以卖家身份登录的!
答案 1 :(得分:0)
您可能必须在过滤器之前设置以验证查看器
class ItemsController < ActionController::Base
before_action :authenticate_viewer!
def show
...
end
end