【发布时间】:2019-01-13 16:02:08
【问题描述】:
我正在尝试让User 收藏coffee_roast。然而,在尝试加载显示页面时,我得到一个 NoMethod 错误
未定义的方法`favorite_coffee_roast_path'
来自这行代码:
<%= link_to "Add to favorites", favorite_coffee_roast_path(@coffee_roast, type: "favorite"), method: :put %><br />
我尝试了多种变体,例如:
favorite_roast_coffee_roast_pathfavorite_coffeeroast_coffee_roast_pathfavorite_coffee_roast_coffee_roast_path
显然没有任何作用。
我的模型
class User < ApplicationRecord
has_merit
has_one :drink
has_many :coffeeshops
has_many :coffee_roasts
has_many :favorite_coffeeroasts
has_many :favorite_roasts, through: :favorite_coffeeroasts, source: :coffee_roast
class CoffeeRoast < ApplicationRecord
has_many :favorite_coffeeroasts
has_many :favorited_by, through: :favorite_coffeeroasts, source: :user
class FavouriteCoffeeroast < ApplicationRecord
belongs_to :coffee_roast
belongs_to :user
我的控制器
class CoffeeRoastsController < ApplicationController
...
def favorite_coffeeroast
@coffee_roast = CoffeeRoast.find(params[:id])
type = params[:type]
if type == "favorite"
current_user.favorite_roasts << @coffee_roast
redirect_to @coffee_roast, notice: "You favorited #{@coffee_roast.name}"
elsif type == "unfavorite"
current_user.favorite_roasts.delete(@coffee_roast)
redirect_to @coffee_roast, notice: "Unfavorited #{@coffee_roast.name}"
else
# Type missing, nothing happens
redirect_to @coffee_roast, notice: "Nothing happened."
end
end
routes.rb
Rails.application.routes.draw do
#core root
get 'home/index' => 'home#index'
root 'home#index'
#roasts redirect
get '/roasts', to: redirect('/coffee_roasts', status: 302)
namespace :api do
namespace :v1 do
resources :roasts
end
end
resources :blends
resources :roasters
resources :countries
resources :regions
resources :comments
resources :coffee_flavours
resources :flavours
resources :drinks
devise_for :users
devise_for :admins
resources :varietals
resources :tags
resources :coffee_beans
resources :coffee_roasts
resources :processings
get 'contact-me', to: 'messages#new', as: 'new_message'
post 'contact-me', to: 'messages#create', as: 'create_message'
#static pages
get 'about', to: 'pages#about'
get 'cookiepolicy', to: 'pages#cookiepolicy'
get 'map', to: 'pages#map'
get 'longblack', to: 'longblack#index'
get 'prices', to: 'prices#new'
post 'prices', to: 'prices#create'
#db resources
resources :roasters do
resources :comments
end
resources :articles do
resources :comments
end
resources :coffeeshops do
resources :comments
end
resources :roasts do
resources :comments
end
resources :coffee_roasts do
resources :comments
end
resources :coffeeshops do
put :favorite, on: :member
end
resources :coffeeshops do
put :bookmarked, on: :member
end
为什么我找不到正确的路径?我错过了什么?
【问题讨论】:
-
我可以知道你的 config/routes.rb
-
刚刚添加的路线
-
您好像忘记在路由文件中添加
favorite_coffeeroast操作了:) 之后您可以在终端中使用rake routes | grep favorite命令找到正确的路径名 -
感谢@Vasilisa 我添加了
resource :favorite_coffeeroast并且页面现在加载,但是当尝试“收藏”时我得到uninitialized constant FavoriteCoffeeroastController
标签: ruby-on-rails activerecord associations