0

我有一个正在运行的友谊模型,但是当我在我的用户/显示视图中包含此代码时,我得到了这个不需要的结果:

Friends
Dave Olson, accepted

[#<Friendship id: 74, user_id: 1, friend_id: 2, status: "accepted", created_at: "2014-03-27 03:54:08", updated_at: "2014-03-27 03:54:09">]

我无法弄清楚为什么会打印出额外的哈希。

这是我认为的代码:

<h3>Friends</h3>
<%= @user.friendship.each do |friendship| %>
<p><%= friendship.friend.name %>, <%= friendship.status %></p>
<% end %>

用户模型是:

class User < ActiveRecord::Base
  rolify
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :invitable, :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable

         has_many :items
         has_many :friendship
end

以及我的友谊模型的相关部分:

class Friendship < ActiveRecord::Base

    belongs_to :user
    belongs_to :friend, class_name: "User", foreign_key: "friend_id"

    validates_presence_of :user_id, :friend_id
....more code
end

我能够消除哈希的唯一方法是不运行该块。不幸的是,这行不通。那么,为什么哈希会打印出来呢?我曾尝试寻找答案,但没有任何成功。任何帮助将不胜感激。

4

2 回答 2

5

从循环=中使用的 erb scriptlet 中删除等号:each

<h3>Friends</h3>
<% @user.friendship.each do |friendship| %>
  <p><%= friendship.friend.name %>, <%= friendship.status %></p>
<% end %>

您看到不需要的哈希的原因是因为<%=<%用于打印输出相反。因此,<%= @user.friendship.each...打印该each块返回的结果。

于 2014-03-27T04:20:08.060 回答
2

简单的说

这个标签会输出一些东西

<%= ... %>

这个标签不会

<% ... %>
于 2014-03-27T04:35:09.347 回答