ruby-on-rails - NoMethodError - Rails - 无法追踪问题
问题描述
我目前正在开发一个博客应用程序。该博客有用户、故事和收藏夹。1 个用户可以有很多故事和很多收藏夹,一个故事也可以有很多收藏夹(每个用户 1 个)。
当我尝试在前端(create
路由)上保存新收藏时,我收到以下错误:
undefined method `favourites' for #<Class:0x00007f850e24e290>
Extracted source (around line #11):
9 def create
10 @story = Story.find(params[:story_id])
11 @favourite = Story.favourites.new
12 @favourite.user = @current_user
13 @favourite.save
14 redirect_to story_path(@story)
我觉得这应该被定义,并且几乎与我create
与其他控制器一起使用的方式相同。根据我到目前为止的发现,我怀疑这是因为favourites
inStory.favourites.new
嵌套在 Story 中,但我还没有找到一种方法来解决它。我对 Rails 很陌生,所以如果答案很明显,我很抱歉。任何指导表示赞赏!谢谢你的帮助!
下面是一些相关的文件。
favourites_controller.rb
class FavouritesController < ApplicationController
before_action :logged_in, except: [:index, :show]
def show
end
def create
@story = Story.find(params[:story_id])
@favourite = Story.favourites.new
@favourite.user = @current_user
@favourite.save
redirect_to story_path(@story)
end
end
故事控制器.rb
class StoriesController < ApplicationController
before_action :logged_in, except: [:index, :show]
# Stories list page (also homepage)
def index
# Topic filtering
@topic = params[:topic]
@stories = if @topic.present?
Story.where(topic: @topic)
else
Story.all
end
end
def new
@story = Story.new
end
def create
@story = Story.new(form_params)
@story.user = @current_user
if @story.save
redirect_to root_path
else
render 'new'
end
end
def show
@story = Story.find(params[:id])
end
def destroy
@story = Story.find(params[:id])
@story.destroy if @story.user == @current_user
redirect_to root_path
end
def edit
@story = Story.find(params[:id])
redirect_to root_path if @story.user != @current_user
end
def update
@story = Story.find(params[:id])
if @story.user == @current_user
if @story.update(form_params)
redirect_to story_path(@story)
else
render 'edit'
end
else
redirect_to root_path
end
end
def form_params
params.require(:story).permit(:title, :topic, :body)
end
end
模型/收藏夹.rb
class Favourite < ApplicationRecord
belongs_to :story
belongs_to :user
validates :story, uniqueness: { scope: :user }
end
模型/story.rb
class Story < ApplicationRecord
has_many :comments
has_many :favourites
belongs_to :user
validates :title, presence: true
validates :body, presence: true, length: { minimum: 10 }
def to_param
id.to_s + '-' + title.parameterize
end
end
配置/路由.rb
Rails.application.routes.draw do
resources :stories do
resources :comments
resource :favourite
end
resources :users
resource :session
root 'stories#index'
end
解决方案
问题出在这一行:
11 @favourite = Story.favourites.new
它应该是:
11 @favourite = @story.favourites.new
因为类Story
本身没有favourites
方法,但它的实例有。
推荐阅读
- python - 使用 cURL 通过 Firebase 发送通知不起作用
- javascript - HTML元素上的Javascript onclick事件
- android - 运行后一个应用程序的两个相同图标
- firebase - 您的 Cloud Firestore 数据库具有不安全的规则 - flutter firebase db
- python - 是否可以将一个功能拆分为多个功能并且仍然具有连续性/原始结果
- visual-studio - 如何在 Visual Studio 2017 中取消选中 Visual Studio 的 Windows 混合现实模板
- c# - Unity - 在某些点的瓷砖边缘之间可见背景
- c - 如何在 C 中返回格式化的字符串?
- performance - EX 秒会影响 Redis 中的性能吗?
- rust - 使用字符串访问向量元素