【问题标题】:Couldn't find User with 'id'=#<User:0x007f88b1d4f9e0>找不到具有 'id'=#<User:0x007f88b1d4f9e0> 的用户
【发布时间】:2015-10-27 02:55:33
【问题描述】:

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

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 %>

【问题讨论】:

  • 问题在于提交的内容;您将传递给用户的 to_s 而不是用户 ID。
  • 哦,很好。我不知道为什么那个用户对象被包裹在一个字符串中
  • 请张贴form代码。
  • &lt;%= form_for @user_friendship, method: :post do |f| %&gt; &lt;div class="form form-actions"&gt; &lt;%= f.hidden_field :friend_id, value: @friend %&gt; &lt;%= submit_tag "Yes, Add Friend", class: 'btn btn-primary' %&gt; &lt;%= link_to "Cancel", user_path(@friend), class: 'btn btn-danger' %&gt; &lt;/div&gt; &lt;% end %&gt;
  • 哦,我的意思是在问题中添加它。

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


【解决方案1】:

你应该改变这一行

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

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

【讨论】:

  • 就是这样。只需将 id 添加到@friend。格拉西亚斯
猜你喜欢
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 2019-12-17
  • 2016-10-19
相关资源
最近更新 更多