Javascript 使用Ruby数组迭代并使用JS在视图中显示
我正在尝试进行一个ajax调用,该调用将返回一个对象数组并在视图中显示它。。我可以显示类位置的单个对象,但不能遍历数组。我得到以下错误Javascript 使用Ruby数组迭代并使用JS在视图中显示,javascript,ruby-on-rails,Javascript,Ruby On Rails,我正在尝试进行一个ajax调用,该调用将返回一个对象数组并在视图中显示它。。我可以显示类位置的单个对象,但不能遍历数组。我得到以下错误 ActionView::Template::Error (undefined method `model_name' for NilClass:Class): 我的js文件是 $("#locations").append("<%= escape_javascript(render(@locations)) %>"); 当我传递ActiveRec
ActionView::Template::Error (undefined method `model_name' for NilClass:Class):
我的js文件是
$("#locations").append("<%= escape_javascript(render(@locations)) %>");
当我传递ActiveRecord对象数组时,我认为这与序列化有关 假设结果的大小是5,那么
@locations=Array.new(result.size)
将返回[nil,nil,nil,nil,nil]
然后将位置推送到该阵列
[nil, nil, nil, nil, nil, location1, location2, ...]
然后你就可以看到你的错误了。我发现了问题所在。。。我之所以会出现错误,是因为我已经创建了@locations=Array.new(result.size),这会创建一组nil对象,而迭代时会抛出错误。。
def search
result = getResultFromSomeWhere
@locations = Array.new(result.size)
result.each do |resultobj|
@locations.push(Location.new(resultobj))
end
respond_to do |format|
format.js
end
end
[nil, nil, nil, nil, nil, location1, location2, ...]