Ruby/Rails - .each Iterator 在循环结束时打印整个数组 [英] Ruby / Rails - .each Iterator is printing entire array at the end of the loop

查看:41
本文介绍了Ruby/Rails - .each Iterator 在循环结束时打印整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我想要做的很简单,我真的不知道为什么这不起作用.我正在使用 Rails 3.

I think what I'm trying to do is pretty simple, and I'm really not sure why this isn't working. I'm using Rails 3.

本质上,我只是想从现有模型的列中选择不同的值,然后将它们全部打印出来.在大多数情况下,这是有效的,但我认为 .each 循环也会在循环结束时打印整个数组.(

Essentially, I'm just trying to select the distinct values from a column in an existing model, and print them out all. For the most part, this works but the .each loop in my view also ends up printing the entire array at the end of the loop. (

我有一个名为 Attractions 的模型,每个景点都有一个类别(现在为了简单起见,类别在 DB 中进行了硬编码).

I a model called Attractions, and each attraction has a Category (right now the Category is hardcoded in the DB for simplicity).

这是吸引力模型和定义的类方法all_categories"...

This is the Attraction Model and a class method "all_categories" defined...

class Attraction < ActiveRecord::Base

  def self.all_categories
    Attraction.select("DISTINCT category")
  end

end

这是吸引力控制器

class AttractionsController < ApplicationController
  def index
    @categories = Attraction.all_categories
    @attractions = Attraction.find(:all)
  end

  def show
    @attraction = Attraction.find(params[:id])
  end
end

在我看来,这是导致麻烦的代码 - 没有火箭科学,只是一个简单的迭代器,......

This is the code in my view that is causing trouble - no rocket science, just a simple iterator, ...

  <%= @categories.each do |c| %>
    <%= c.category %><br/>
  <% end %>

很简单吧?这一切都运行良好,但这是我在运行该代码段时看到的:

Pretty simple, right? This is all running fine, BUT this is what I see when that code segment is run:

Architecture
Art
Fashion
Music
[#<Attraction category: "Architecture">, #<Attraction category: "Art">, #<Attraction category: "Fashion">, #<Attraction category: "Music">]

为什么要打印末尾的数组?我想要的只是一个类别列表:

Why is the array at the end printed? All I want is a list of the categories:

Architecture
Art
Fashion
Music

显然,我是 Ruby/Rails 的新手,我已经尝试四处寻找解决方案.有什么明显我遗漏的地方吗?

Obviously, I'm new to Ruby/Rails, and I've tried to search all over for a solution to this. Is there something obvious that I'm missing?

感谢任何帮助.

推荐答案

# Change this line with an =:
<%= @categories.each do |c| %>
# ...to this:
<%  @categories.each do |c| %>

您只需要对 #each 方法的块产生副作用,而不需要对返回值进行插值.

You only want the side effects on the block of the #each method, you don't want interpolation of the returned value.

这篇关于Ruby/Rails - .each Iterator 在循环结束时打印整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆