我对rails和编写我的第一个应用程序相当新。只是无法弄清楚如何将用户定位为current_user(三种模式:User,Tool,FavoriteUser)。
控制器(工具)
def index
@favorites = current_user.favorites.order("created_at DESC")
@userfavorites = current_user.userfavorites.order("created_at DESC")
@tools = Tool.where(user_id: current_user).order("created_at DESC")
@user = current_user.favorite_user # problematic!
@cuser = current_user
end
索引视图(工具)
%h2 My Favorite Users
- @userfavorites.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", userfavorite_user_path(user, type: "favorite"), method: :get
%p= link_to "Unfavorite", userfavorite_user_path(user, type: "unfavorite"), method: :get
如果我在浏览器中运行它,则会出现以下错误:
NoMethodError in ToolsController#index
undefined method `favorite_user' for #<User:0x39df638>
FavoriteUser数据库:
user_id:integer #favorited
c_user_id:integer #active user
我根本无法弄明白。
在此先感谢您的帮助!
关系:
user.rb
has_many :favorite_users # just the 'relationships'
# Favorite users of user
has_many :favorite_relationships, class_name: "FavoriteUser", foreign_key: "c_user_id"
has_many :userfavorites, through: :favorite_relationships, source: :user
# Favorited by a user
has_many :favorited_relationships, class_name: "FavoriteUser", foreign_key: "user_id"
has_many :userfavorited_by, through: :favorited_relationships, source: :c_user
favorite_user.rb
class FavoriteUser < ActiveRecord::Base
belongs_to :c_user, class_name: "User"
belongs_to :user, class_name: "User"
end
路线
Rails.application.routes.draw do
devise_for :users
get 'welcome/index'
resources :tools do
member do
get "like", to: "tools#upvote"
get "dislike", to: "tools#downvote"
end
get :favorite, on: :member
end
resources :users, only: [:index, :show] do
get :userfavorite, on: :member
end
authenticated :user do
root 'tools#index', as: "authenticated_root"
end
root 'welcome#index'
get '/search' => 'tools#search'
get '/users' => 'users#index'
end
答案 0 :(得分:1)
改变这个:
@user = current_user.favorite_user
为:
@favorite_users = current_user.favorite_users
user
has_many favorite_users
请勿忘记在调用@user
的地方重命名实例变量。
答案 1 :(得分:0)
这就是解决方案!
@userfavorites = current_user.userfavorites