Rails 4错误:NoMethodError / undefined方法

时间:2016-09-05 16:17:18

标签: ruby-on-rails ruby ruby-on-rails-4 methods undefined


嘿那里,
我是Rails的新手,我已经设法为我的项目(工具)和用户创建了一个受欢迎的控制器,它完全正常。
现在我正在尝试在该用户模块中执行相同操作。因此,用户可以喜欢其他用户。

我玩过,并想出了这个:

访问/ users / index视图时,我在浏览器中收到此错误:

NoMethodError in Users#index
undefined method `favorite_user_path' for #<#<Class:0x8ca77b8>:0x8ca50b8>

这是我的代码:

应用程序/模型/ favorite_user.rb

class FavoriteUser < ActiveRecord::Base
    belongs_to :c_user_id
    belongs_to :user_id
end

应用程序/模型/ user.rb

class User < ActiveRecord::Base

  # Include default devise modules. Others available are:

  # :confirmable, :lockable, :timeoutable and :omniauthable

  devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable


  has_many :tools

  # Favorite tools of user
  has_many :favorite_tools # just the 'relationships'
  has_many :favorites, through: :favorite_tools, source: :tool # the actual tools the user favorites

  # Favorite users of user
  has_many :favorite_users # just the 'relationships'
  has_many :userfavorites, through: :favorite_users, source: :user # the actual users the user favorites
  has_many :userfavorited_by, through: :favourite_users, source: :user # the actual users favoriting a user



  mount_uploader :avatar_filename, AvatarUploader

end

应用程序/控制器/ users_controller.rb

class UsersController < ApplicationController
    before_action :find_user, only: [:show, :favorite]

    # Add and remove favorite recipes
    # for current_user
    def userfavorite
      type = params[:type]
      if type == "favorite"
        current_user.userfavorites << @user

      elsif type == "unfavorite"
        current_user.userfavorites.delete(@user)

      else
        # Type missing, nothing happens
        redirect_to :back, notice: 'Nothing happened.'
      end
    end

    def index
        @users = User.all
    end

    def show
        @tools = Tool.where(user_id: @user).order("created_at DESC")
        @tool = Tool.find(1)
    end

    private

    def find_user
        @user = User.find(params[:id])
    end
end

应用程序/视图/用户/ index.html.haml

- @users.each do |user|
    = image_tag gravatar_for user if user.use_gravatar == true
    = image_tag user.avatar_filename.url if user.use_gravatar == false
    %h2= link_to user.username, user
    %p= link_to "Favorite", favorite_user_path(user, type: "favorite"), method: :get
    %p= link_to "Unfavorite", favorite_user_path(user, type: "unfavorite"), method: :get

应用程序/配置/ routes.rb中

resources :users, only: [:index, :show, :userfavorite] do 
    get :userfavorite, on: :member
end

我希望提供的数据足够,如果没有请告诉我。我很感谢你的回复。

1 个答案:

答案 0 :(得分:1)

您尚未在路线文件中声明任何此类路径。根据您的路线文件,您可以使用命名路径,如

userfavorite_user_path(user_id)