Rails 4中的不需要的哈希打印

时间:2014-03-27 04:18:15

标签: ruby-on-rails ruby-on-rails-4 ruby-2.1

我有一个友好的模型,但是当我在我的用户/节目视图中包含此代码时,我得到了这个不需要的结果:

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

我能够消除散列的唯一方法是不运行块。不幸的是,这不会起作用。那么,为什么哈希打印出来?我试过寻找答案但没有取得任何成功。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分:2)

简单地说

此标记将输出

<%= ... %>

此标记不会

<% ... %>