无方法错误 - 轨道 - 无法跟踪问题



我目前正在开发一个博客应用程序。博客有用户、故事和收藏夹。一个用户可以有许多故事和许多收藏夹,一个故事也可以有许多收藏夹(每个用户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与其他控制器一起使用的方式几乎相同。根据我目前的发现,我怀疑这是因为Story.favourites.new中的favourites嵌套在Story中,但我还没有找到解决问题的方法。我是Rails的新手,所以如果答案很明显,我很抱歉。感谢您的指导!谢谢你的帮助!

以下是一些相关文件。

preferentes_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

stories_controller.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

models/preferente.rb

class Favourite < ApplicationRecord
belongs_to :story
belongs_to :user
validates :story, uniqueness: { scope: :user }
end

模型/故事.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

config/routes.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方法,但它的实例有

最新更新