简体   繁体   中英

Rails 4 Error: ActiveRecord::RecordNotFound Couldn't find 'id'=

I'm fairly new to rails and into coding my first app. Just can't figure out how to target a user the current_user favorited (Three models: User, Tool, FavoriteUser).

Controller (Tools)

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

Index View (Tools)

%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

If I run this in my browser it appears following error:

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

EDIT:

FavoriteUser Database:

user_id:integer #favorited
c_user_id:integer #active user

I simply can't figure it out.

Thanks in advance for your help!

ADDED RELATIONSHIPS:

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

If you have setup your relationships correctly, following solution should work for you.

Replace:

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

with

# Returning complete user object instead of only user's id,
# as it's getting used on the view
@user = current_user.favorite_user
params[:c_user_id]

is nil when this controller action is invoked. You have to send it through if you want to access it. If you put this line at the top of your controller action

puts "#{params[:c_user_id]}"

you will see params[:c_user_id] is nil.

那就是解决方案!

@userfavorites = current_user.userfavorites

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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