0

アプリにサインインしていないユーザー プロファイル ページにアクセスすると、アプリで次のエラーが発生します (Devise を使用しています)。

UsersController の NoMethodError#nil:NilClass の未定義メソッド「connections」を表示

app/controllers/users_controller.rb:19:in `show'

ログインするとエラーが消えます。失敗する理由はわかっています。適切な解決策を考え出す手助けが必要です。

ユーザーコントローラーの次の行でエラーが発生します。

def show
@connection = current_user.connections.build(user_id: current_user, otheruser_id: @user)
end

アプリにログインしているユーザーには、接続フォームが表示されます (簡単に言えば、この人と友達として接続するかどうかを尋ねるボタンが表示されます)。<% if user_signed_in? %>ただし、フォームの前にユーザービューの「表示」ページにユーザーがログインしているかどうかを確認しています。

ビューからの関連コードは次のとおりです。

 <%= render 'connect_form' if user_signed_in? %>

connect_form

<% unless current_user == @user %>
  <% if @contact.present? && user_signed_in? %>
      <%= @user.first_name %> is your  <%= @contact.description %> (<%= link_to "edit contact", edit_connection_path(:id => @contact.id, :user => @user) %>)<br \>
  <% else %>
    <% if user_signed_in? %>How do you know <%= @user.first_name %>? (<%= link_to "edit contact", new_connection_path(:user => @user) %> )
  <% else %> 
<% end %><br \>
<% end %>
<% end %>

connection_form (新規作成)

<% if user_signed_in? %>
How do you know <%= @user.first_name %>?
  <%= form_for(@connection) do |f| %>
  <%= f.collection_select :description, Connection::CONNECTIONTYPE, :to_s, :to_s, :include_blank => true %>
  <%= f.hidden_field(:otheruser_id, :value => @user.id) %>
  <%= f.submit "Save", class: "btn btn-primary btn-small" %>
  <% else %>
<% end %>

user_signed_in をチェックしているのに、アプリが nil 配列 `@connections を読み込もうとするのはなぜですか? どんな助けでも大歓迎です!!

4

2 に答える 2

1

First thing I would do is put a check to only build the connection if the current user exist.

def show
  @connection = current_user.connections.build(user_id: current_user, otheruser_id: @user) if current_user
end

The main thing to notice is the: if current_user at the end of the line

于 2013-07-18T00:23:31.687 に答える
0

エラーメッセージより

undefined method `connections' for nil:NilClass

current_userはnilです。これを簡単にテストするには

def show @connection = User.new.connections.build(user_id: current_user, otheruser_id: mock_user_id) end

あなたの場合、ログインユーザーをどこかに保存していない可能性があります

于 2013-07-18T00:24:17.767 に答える