0

私は Michael Hartl の ruby​​ on rails チュートリアルをあまり問題なく進めています (少なくとも、少し調べたり、考えたり、検索したりするだけでは解決できませんでした)。第11章の関係モデルを実装します。

具体的には、フォロー/フォロー解除ボタンを押すと、次のエラーが返されます。

ActiveRecord::RecordNotFound in RelationshipsController#create
Couldn't find User with id=#<User:0x007f3288020d98>
Extracted source (around line #5):

def create
@user = User.find(params[:relationship][:followed_id])
current_user.follow!(@user)
redirect_to @user
end

問題は、検索しているユーザー ID が # のようなものではなく整数である必要があることだとわかりますが、ユーザー ID ではなく 16 進コードのように見えるものを検索する理由がわかりません。

RelationshipsController は、チュートリアルで指定されているものとまったく同じです。

class RelationshipsController < ApplicationController
  before_action :signed_in_user

  def create
    @user = User.find(params[:relationship][:followed_id])
    current_user.follow!(@user)
    redirect_to @user
  end

  def destroy
    @user = Relationship.find(params[:id]).followed
    current_user.unfollow!(@user)
    redirect_to @user
  end
end

私が考えることができる唯一の重要な違いは、sqlite の代わりに postgres を使用していることですが、postgres への切り替えが演習として与えられたので、この種の問題が発生するとは想像できません。

同様の問題を検索してみましたが、何も見つかりませんでした。

(編集)

フォロー/フォロー解除ボタンをレンダリングするフォームは次のとおりです。

<% unless current_user?(@user) %>
    <div id="follow_form">
        <% if current_user.following?(@user) %>
            <%= render 'unfollow' %>
        <% else %>
            <%= render 'follow' %>
        <% end %>
    </div>
<% end %>

そしてボタン自体:

<%= form_for (current_user.relationships.build(followed_id: @user)) do |f| %>
    <div><%= f.hidden_field :followed_id %></div>
    <%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>

<%= form_for(current_user.relationships.find_by(followed_id: @user), html: { method: :delete }) do |f| %>
  <%= f.submit "Unfollow", class: "btn btn-large" %>
<% end %>

UsersController の show メソッドは

class UsersController < ApplicationController
  before_action :signed_in_user, only: [:index, :edit, :update, :destroy, :following, :followers]
  before_action :correct_user, only: [:edit, :update]
  before_action :admin_user, only: :destroy
  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.paginate(page: params[:page])
    if current_user?(@user)
      @micropost = current_user.microposts.build
    end
  end
  .
  .
  .
4

1 に答える 1

0

ユーザー オブジェクト自体ではなく、ユーザーの ID が必要なため、パーシャルを次のように変更followします。

followed_id: @user.idそれ以外のfollowed_id: @user

于 2013-11-06T02:40:45.467 に答える