开发者

How to iterate over multiple model results in Rails 3?

开发者 https://www.devze.com 2023-01-23 22:29 出处:网络
I am not sure what I am doing wrong here. I find many examples that show that I am doing this right and it is really basic stuff, I know.

I am not sure what I am doing wrong here. I find many examples that show that I am doing this right and it is really basic stuff, I know.

I am simplyfying a bit, but I have two models, 'Post' and 'Category'. I am trying to get the list of categories from the database and list them by name.

class Post < ActiveRecord::Base
   has_and_belongs_to_many :categories  
end

class Category < ActiveRecord::Base
   has_and_belongs_to_many :posts  
end

# get all categories and output the names
cats = Category.all
cats.each do |cat|
   cat.name
end

It instead seems to output the entire array of retrieved results. All results not even just the one I am iterating over. What 开发者_JS百科gives?


Where are you putting that .each loop code? Where is the "output" code you're referring to? If you're using a loop in a view, make sure you're using

<% %>

and not

<%= %>

for the loop lines themselves. As in:

<% Category.all.each do |cat| %>
  <%= cat.name %>
<% end %>


Category.all returns an array of all Category objects, which is everything the categories table contains. cats is therefore an array of all the categories. I'm not sure why you think you're only iterating over "one" of anything. To get one result, you can use find() or first:

cat = Category.first
puts cat.name

If you want all the names, you can do this:

Category.all.map(&:name)

or, a bit more efficiently, especially if there are many fields:

Category.all(:select => :name).map(&:name)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号