繁体   English   中英

Rails 4错误:NoMethodError /未定义的方法

[英]Rails 4 Error: NoMethodError / undefined method


嘿,
我对Rails相当陌生,并且设法为我的Items(Tools)和Users创建了一个Favorite控制器,该控制器工作得很好。
现在,我试图在该用户模块中执行相同的操作。 因此,用户能够收藏其他用户。

我玩了一下,想到了这个:

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

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

这是我的代码:

app / models / favorite_user.rb

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

app / models / 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

app / controllers / 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

app / views / users / 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

app / config / routes.rb

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

我希望所提供的数据足够,否则请告诉我。 感谢您的所有答复。

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

userfavorite_user_path(user_id)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM