我已经对此进行了广泛的搜索(也许我搜索错了),但我似乎找不到任何答案。我的目标是遍历数据库中的一堆评论并将信息输出到我的视图中。不幸的是,我的.each do
块似乎没有工作。
模型/comment.rb
class Comment < ActiveRecord::Base
attr_accessible :content, :photo_id, :user_id
belongs_to :user
belongs_to :photo
.
控制器/photos_controller.rb
def show
@photos = Photo.all
@photo = Photo.find(params[:id])
@user_likes = user_likes(@photo.id)
@comments = Comment.find_all_by_photo_id(@photo.id)
.
意见/照片/show.html.erb
<% if !@comments.blank? %>
<% @comments.each do |c| %>
<%= link_to c.user.name, c.user_id %><br />
<%= c.content %>
<% end %>
<% end %>
.
如果我使用@comments.each do |c|, c.(anything)
,它不会返回任何内容。我也在 Rails 控制台中验证了这一点。但是,@comments.first.content
或者@comments.first.user.name
将返回我正在寻找的内容。为什么.first
允许我返回内容和用户字段,但.each do |c|
什么也不返回?
这是 rails 控制台的输出:
1.9.3-p385 :072 > @comments.each do |c|
1.9.3-p385 :073 > c.content
1.9.3-p385 :074?> end
=> [#<Comment id: 1, user_id: 8, photo_id: 27, content: "lalala", created_at: "2013-04-09 15:36:22", updated_at: "2013-04-09 15:36:22">, #<Comment id: 2, user_id: 8, photo_id: 27, content: "abcd", created_at: "2013-04-09 15:42:00", updated_at: "2013-04-09 15:42:00">, #<Comment id: 3, user_id: 8, photo_id: 27, content: "abadsf", created_at: "2013-04-09 15:58:33", updated_at: "2013-04-09 15:58:33">, #<Comment id: 4, user_id: 8, photo_id: 27, content: "asdf", created_at: "2013-04-09 15:59:12", updated_at: "2013-04-09 15:59:12">]
1.9.3-p385 :075 > @comments.first.content
=> "lalala"