找不到'id'=#user:0x007f88b1d4f9e0>的用户

时间:2015-08-04 15:47:07

标签: ruby-on-rails ruby-on-rails-4 hash params

我遇到了这个问题,看起来我在控制器的create方法中正确遍历了params hash,但是出了点问题。

user_friendships_controller.rb

class UserFriendshipsController < ApplicationController
before_filter :authenticate_user!, only: [:new]

def new
    if params[:friend_id]
        @friend = User.find(params[:friend_id])
        @user_friendship = current_user.user_friendships.new(friend: @friend)
    else
        flash[:error] = "Friend required"
    end
rescue ActiveRecord::RecordNotFound
    render file: 'public/404', status: :not_found
end

def create
    if params[:user_friendship] && params[:user_friendship].has_key?(:friend_id)
        @friend = User.find(params[:user_friendship][:friend_id])
        @user_friendship = current_user.user_friendships.new(friend: @friend)
        @user_friendship.save
        flash[:success] = "You are now friends with #{@friend.first_name.titleize}!"
        redirect_to user_path(@friend)
    else
        flash[:error] = "Friend required"
        @user_friendship = current_user.user_friendships.new(friend: @friend)
    end
end
end

错误在第17行@friend = User.find(params [:user_friendship] [:friend_id])

Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"p8hBlY50rLH4477juS4tAoo2aWiEaUD6oSzuCzxPTiU=",
 "user_friendship"=>{"friend_id"=>"#<User:0x007f88b1d4f9e0>"},
 "commit"=>"Yes,
 Add Friend"}

这是指向create方法的表单

<%= form_for @user_friendship, method: :post do |f| %>
    <div class="form form-actions">
        <%= f.hidden_field :friend_id, value: @friend %>
        <%= submit_tag "Yes, Add Friend", class: 'btn btn-primary' %>
        <%= link_to "Cancel", user_path(@friend), class: 'btn btn-danger'  %>
    </div>
<% end %>

1 个答案:

答案 0 :(得分:3)

你应该改变这一行

<%= f.hidden_field :friend_id, value: @friend %>

<%= f.hidden_field :friend_id, value: @friend.id %>