Rails 4错误:ActiveRecord :: RecordNotFound找不到'id'=

时间:2016-09-06 15:04:39

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord controller

我对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 = FavoriteUser.find(params[:c_user_id]).user_id
  @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

如果我在浏览器中运行它,则会出现以下错误:

ActiveRecord::RecordNotFound in ToolsController#index
Couldn't find FavoriteUser with 'id'=

修改

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

3 个答案:

答案 0 :(得分:2)

如果您已正确设置关系,则以下解决方案应该适合您。

替换:

echo $output['url']; //here is the url that you want.

@user = FavoriteUser.find(params[:c_user_id]).user_id

答案 1 :(得分:0)

params[:c_user_id]
调用此控制器操作时,

为nil。如果要访问它,则必须通过它发送。如果您将此行放在控制器操作的顶部

puts "#{params[:c_user_id]}"

你会看到params [:c_user_id]是零。

答案 2 :(得分:-1)

这就是解决方案!

@userfavorites = current_user.userfavorites