[英]Why do I get this noMethodError error?
这是错误:
NoMethodError in VideosController#update
undefined method `each' for #<Topic:0x1032ee330>
这是应用程序跟踪:
app/models/video.rb:19:in `assign_topics'
app/controllers/videos_controller.rb:41:in `update'
app/controllers/videos_controller.rb:40:in `update'
这是我的assign_topics
方法:
def assign_topics
if @topic_names
self.topics = Topic.find_or_create_by_name(@topic_names)
end
end
请注意,我正在关注以下内容: http : //media.railscasts.com/videos/167_more_on_virtual_attributes.mov
这是视频控制器的更新方法:
def update
@video = current_user.videos.find(params[:id])
respond_to do |format|
if @video.update_attributes(params[:video])
format.html { redirect_to(@video, :notice => 'Video was successfully updated.') }
else
format.html { render :action => "edit" }
end
end
end
之所以会出现NoMethodError Exception
是因为您尝试通过.each()
在代码中某处尝试在非数组/可枚举的对象上循环。
根据您的例外情况,您正在对Model Object(Topic)调用.each()
,因为没有.each()
方法是.each()
。
我猜你的assign_topics
方法有问题。 Topic.find_or_create_by_name
将返回一个Topic
实例,然后将其分配给self.topics
和self.topics
可能期望使用Array
(或其他Enumerble
); 然后,更新过程将尝试使用each
循环遍历self.topics
,您会得到错误。
您在一条评论中提到您尝试了以下操作:
self.topics = @topic_names.each { |n| Topic.find_or_create_by_name(n) }
但这是行不通的,因为each
返回原始数组 ,因此上面的代码与此等效:
@topic_names.each { |n| Topic.find_or_create_by_name(n) }
self.topics = @topic_names
您找到/创建的所有Topic
实例都将被丢弃。
因此,使用如下的collect
可能会带来更好的运气:
def assign_topics
if @topic_names
self.topics = @topic_names.collect { |n| Topic.find_or_create_by_name(n) }
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.