我遇到了这个问题:#<User:0xa8dc8b8>的未定义方法\'each\'

问题描述

|
19: <strong>URL</strong> <%= link_to user_path(@user),(@user)%><br />
20: 
21: <strong>Thoughts</strong> <%= @user.thoughts.count %>
22: <% @user.each do |user| %>
23: <li>
24:   <% if Friendship.are_friends(current_user,user) %>
25:     (you are friends)
它在第22行抛出了错误。我不明白为什么。我只是想为每个朋友做循环。 编辑:1 我实际上是想通过我的社交网络侧栏中的链接发送友谊请求。这是它遗漏的代码:
     <% @user.friendship.each do |user| %>
          <li>
<% if Friendship.are_friends(current_user,user) %>
  (you are friends)
<% elsif current_user != user %>
  (<%= link_to \"request friendship\",:controller => :friendship,:action => :req,:id => user.name %>)
                <% end %>
                </li>
<% end %>

<h2>Your Friends</h2>
<ol>
<% @user.each do |friendship| %>
  <li><%= friendship.friend.name %>,<%= friendship.status %></li>
<% end %>
</ol>
我尝试添加user.friendship,它确实呈现了页面,但是没有添加朋友的链接。     

解决方法

首先,您可能需要多元化化“友谊”。如果用户has_many:friendships,则您的代码应为@ user.friendships.each 其次,@ user.friendships.each将返回友谊,而不是用户。您的模型如何设置?假设您有一个用户模型和一个友谊模型。友谊模型应如下所示:
class Friendship < ActiveRecord::Base
  #attributes should be :person_id,friend_id
  belongs_to :person,:class_name => \"User\"
  belongs_to :friend,:class_name => \"User\"
end
用户模型如下:
class User < ActiveRecord::Base
  has_many :friendships,:foreign_key => \"person_id\",:dependent => :destroy
  has_many :friends,:through => :friendships
end
在这种情况下,您将要使用@ user.friends.each而不是@ user.friendships.each。第一个循环通过一系列用户,第二个循环通过友谊。     ,
@user
是单个记录(一个用户)-您可以使用
.each
遍历记录数组,而不是单个记录。 也许您的意思是
@user.friends.each do |user|
?     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...