【问题标题】:Unwanted hash prints in Rails 4Rails 4 中不需要的哈希打印
【发布时间】:2014-05-05 20:52:11
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

    简单地说

    这个标签会输出一些东西

    <%= ... %>
    

    这个标签不会

    <% ... %>
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2022-12-10
        • 2014-11-30
        • 1970-01-01
        • 2013-06-21
        • 2016-11-01
        • 1970-01-01
        • 2011-10-27
        • 1970-01-01
        • 2017-07-18
        相关资源
        最近更新 更多