Question

I have a friendship model that is working but when I include this code in my user/show view, I get this unwanted result:

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">]

I can't figure out why the extra Hash prints out.

Here's the code from my view:

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

The User model is:

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

And the relevant portion of my Friendship Model:

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

The only way I have been able to eliminate the hash is by not running the block. Unfortunately that isn't going to work. So, why is the hash printing out? I have tried searching for an answer but haven't had any success. Any help would be greatly appreciated.

Was it helpful?

Solution

Remove the equals sign = from the erb scriptlet used in the each loop:

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

The reason you see the unwanted hash is because <%= as opposed to <% is used to print the output. So, <%= @user.friendship.each... prints the result returned by that each block.

OTHER TIPS

Simply put

This tag will output something

<%= ... %>

This tag will not

<% ... %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top