首页 > 解决方案 > 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与其他控制器一起使用的方式相同。根据我到目前为止的发现,我怀疑这是因为favouritesinStory.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

标签: ruby-on-railsruby

解决方案


问题出在这一行:

11 @favourite = Story.favourites.new

它应该是:

11 @favourite = @story.favourites.new

因为类Story本身没有favourites方法,但它的实例有。


推荐阅读