Ruby 未定义的方法'each';nil:NilClass——再一次——我不明白。不断地犯这个错误 class ProfileController
在_pics.html.erb的视图中,我有Ruby 未定义的方法'each';nil:NilClass——再一次——我不明白。不断地犯这个错误 class ProfileController,ruby,ruby-on-rails-3,Ruby,Ruby On Rails 3,在_pics.html.erb的视图中,我有 class ProfileController < ApplicationController def show @user = current_user @first_name = @user.first_name @last_name = @user.last_name end def settings end def pics @photos = current_user.photos.all end
class ProfileController < ApplicationController
def show
@user = current_user
@first_name = @user.first_name
@last_name = @user.last_name
end
def settings
end
def pics
@photos = current_user.photos.all
end
end
如果我将其更改为current_user.photos.each do | p |,它会工作,这很奇怪。我的另一台计算机上的代码没有错误。您在评论中说,您从
show
视图中呈现pics
部分。由于show
视图由show
操作呈现,并且show
操作没有设置@photos
变量,因此不能使用该变量。因此,要解决问题,需要在show
操作中设置变量
您似乎认为渲染pics
部分将调用pics
操作,但事实并非如此。仅当使用路由系统访问映射到该URL的URL时,才会调用操作。呈现部分不会调用任何操作
另外,它应该是
@photos=current_user.photos
,而不是all
,您在哪个控制器操作中?你确定调用过pics方法吗?确切地说,你是如何渲染pics.html.erb的?点击“pics”操作将呈现pics.html.erb,而在配置文件的视图中,我有一个_pics.html.erb。我称之为_pics.html.erb中的“@photos”。我不熟悉rails。我想因为我在profile controller中声明了def pics和@photos,所以_pics.html.erb将自动知道“@photos”是什么。我只是错误地理解了控制器及其视图吗?我将图片渲染为div中show.html.erb的一部分,如果渲染show.html.erb
,则需要在show
操作中定义@photos
。仅在show中呈现\u pics
部分不会调用controller.edit中的pics
操作,摆脱all方法解决了问题。谢谢
<% @photos.each do |p| %>
<%= image_tag p.image(:medium) %>
<% end %>