Rails视图从哈希打印我们想要的某些值,然后是完整的哈希 - 为什么?

时间:2014-07-31 21:12:06

标签: ruby-on-rails view hash controller

我们正在尝试构建提交的评论和文章的Feed,只调用并显示每个评论和文章的某些属性。我们能够获得各种各样的提要,但页面也返回了文章和评论的所有属性的哈希值。见下文:

控制器:

  def show
        @user = User.find(params[:id])
      # @feed= (Article.all + Comment.all).sort!{|a,b| a.updated_at <=> b.updated_at}.reverse.take(10)

  comments = Comment.all
  comments_array = []
  comments.each do |f|
    comment_info ={}
    comment_info['feed_text'] = f.commenter + ' submitted to a goal'
    comment_info['time_stamp']=f.updated_at
    comments_array<<comment_info
  end

  articles=Article.all
  articles_array =[]
  articles.each do |f|
    article_info ={}
    article_info['feed_text']='A new goal has been created:' + f.title
    article_info['time_stamp']=f.created_at
    articles_array<<article_info
  end



  @feed = (comments_array + articles_array).sort!{|a,b| a['time_stamp'] <=> b['time_stamp']}.reverse.take(10)

  end

查看:

        <p>
        <%= @feed.each do |f| %>
        <p>
            <%= f['feed_text'] %>
        </p>
        <% end %>

        </p>

下面显示了页面上显示的内容:

#what_we_want:

2提交目标

新提交目标

创建了一个新目标:测试6

创建了一个新目标:test2

#what_we_don't_want:

[{“feed_text”=&gt;“2提交目标”,“time_stamp”=&gt;星期四,2014年7月31日19:27:40 UTC +00:00},{“feed_text”=&gt;“新提交目标“,”time_stamp“=&gt;星期四,2014年7月31日19:27:31 UTC +00:00},{”feed_text“=&gt;”已创建新目标:测试6“,” time_stamp“=&gt;星期四,2014年7月31日19:27:19 UTC +00:00},{”feed_text“=&gt;”已创建新目标:test2“,”time_stamp“=&gt;星期四,7月31日2014 14:45:09 UTC +00:00}]

我们无法弄清楚为什么页面同时显示#what_we_want和#what_we_don't_want。

1 个答案:

答案 0 :(得分:2)

您想要替换

<%= @feed.each do |f| %>

<% @feed.each do |f| %>

<%=意味着评估/执行代码并将其插入到html中,其中<%意味着简单地评估/执行代码