Ruby on Rails 3 .each 做问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6946206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:43:26  来源:igfitidea点击:

Ruby on Rails 3 .each do Problem

ruby-on-railsruby-on-rails-3hash

提问by Amzziipan

I'm sort of new to Ruby on Rails and have been learning just fine, but have seem to run into a problem that I can't seem to solve.

我是 Ruby on Rails 的新手并且一直在学习,但似乎遇到了一个我似乎无法解决的问题。

Running Rails 3.0.9 & Ruby 1.9.2

运行 Rails 3.0.9 和 Ruby 1.9.2

I'm running the following statement in my View:

我在我的视图中运行以下语句:

<%= @events.each do |f| %>
    <%= f.name %><%= link_to "View", event_path(f) %><br/><hr/>
<% end %>

And this in my controller:

这在我的控制器中:

class AdminController < ApplicationController
  def flyers
    @events = Event.all
  end
end

This goes through each of the records and outputs the appropriate name, but the problem is that at the end it displays all of the information for all of the records like so:

这会遍历每条记录并输出适当的名称,但问题是最后它显示了所有记录的所有信息,如下所示:

    [#<User id: 1, username: "test account", email: "[email protected]", password_hash:    "a$Rxwgy.0ZEOb0lMGEIliPBeB/jPSp8roeKdbMvXcLi32R...", password_salt: "a$Rxwgy.0ZEOb0lMGEIliPBe", created_at: 2111359287.2303703, updated_at: 2111359287.2303703, isadmin: true>]

I'm new to this site, so I'm not sure if you need any more details, but any help is appreciated, after all, I'm still learning.

我是这个网站的新手,所以我不确定您是否需要更多详细信息,但感谢任何帮助,毕竟,我仍在学习。

Thanks in advance.

提前致谢。

回答by Dylan Markow

You should be using <%, not <%=for your .eachline, so

你应该使用<%, 而不是<%=你的.each线路,所以

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

should be

应该

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

回答by Olives

.eachreturns the entire array at the end once it is finished the loop. <%= ... %>prints out the value of the statment, which is the value returned by .each<% ... %>does not. So you want:

.each一旦完成循环,将在最后返回整个数组。 <%= ... %>打印出语句的值,.each<% ... %>即不返回的值。所以你要:

<% @events.each do |f| %>
    <%= f.name %><%= link_to "View", event_path(f) %><br/><hr/>
<% end %>