【问题标题】:NoMethodError in UsersController#show用户控制器中的 NoMethodError#show
【发布时间】:2013-07-17 23:13:57
【问题描述】:

当我访问未登录应用程序的用户个人资料页面时,我的应用程序出现以下错误(我正在使用 Devise):

UsersController#show 中的 NoMethodError nil:NilClass 的未定义方法“连接”

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?非常感谢任何帮助!

【问题讨论】:

  • 你能把用户控制器的内容也放进去吗
  • 您好,感谢您的回复。第一个带有@connection 的代码示例是发生错误的地方。我从用户控制器添加了显示操作以澄清

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

我要做的第一件事是检查是否仅在当前用户存在时才建立连接。

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

主要需要注意的是:if current_user 在行尾

【讨论】:

  • 好主意,但不幸的是它没有改变任何东西:(。我尝试添加 if user_signed_in? 仍然没有。还有其他想法吗?
  • 没关系!非常感谢!发生的事情是在我添加 if current_user 之后,我有一个类似的实例变量,并且在那个变量上触发了错误(错误行号已更改)。我也将 if current_user 添加到该变量的末尾,并且一切正常。再次感谢你
【解决方案2】:

来自错误信息

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

对于您的情况,也许您没有将登录用户存储在某处

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多