我正在尝试允许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_path
favorite_coffeeroast_coffee_roast_path
favorite_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
为什么找不到正确的路径?我想念什么?
答案 0 :(得分:0)
您似乎需要阅读有关routing in ROR的更多信息。将新操作添加到现有的resources :coffee_roasts
:
resources :coffee_roasts do
put :favorite_coffeeroast, on: :member
resources :comments
end
此外,在编写带嵌套和不带嵌套的路由时,都在复制路由。由于您想嵌套到注释路由的所有位置,因此可以不嵌套而删除相应的路由