2013-07-17 27 views
0

,我發現了以下錯誤在我的應用程序,當我訪問用戶的個人資料頁未登入應用程序(我使用的設計):在UsersController#NoMethodError在UsersController#顯示

NoMethodError顯示 未定義的方法'連接的零:NilClass

應用程序/控制器/ users_controller.rb:19:'秀」

當我登錄錯誤消失。我知道它爲什麼失敗。我只需要幫助提出適當的解決方案。

錯誤發生在這條線在我的用戶控制:

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?任何幫助是極大的讚賞!!

+0

您是否可以在用戶控制器中添加內容 –

+0

您好,感謝您的回覆。帶有@ @連接的第一個代碼示例是發生錯誤的地方。我添加了來自用戶控制器的顯示操作來澄清 – winston

回答

1

我要做的第一件事就是檢查一下,只在當前用戶存在時才建立連接。

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

主要的一點需要注意的是:if current_user在該行

+0

好主意,但不幸的是它沒有改變任何東西:(。我嘗試添加如果user_signed_in?並且仍然沒有任何其他想法? – winston

+0

NEVERMIND IT WORKED!非常感謝!發生在我添加後,如果current_user,我有一個類似的實例變量,並在該錯誤發生的錯誤(錯誤行號改變)我添加了如果current_user該變量的結尾,以及一切工作。 – winston

0

年底從錯誤信息

undefined method `connections' for nil:NilClass

current_user是零,一個快速測試,這是

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

對於您的情況,也許您沒有將登錄用戶存儲在某處

相關問題