Ruby for Rails:#array的未定义方法'name':0xb6c971cc> </array:0xb6c971cc>

时间:2010-03-18 18:19:20

标签: ruby-on-rails ruby

我想从mytest表中找到列'name'。

在mytest.rb中,我定义了“attrib_accessor:name”;

在目录/controller/mytest_controller.rb下的过程索引中,

def index
###[Ignore some code]
@mytesttbl=@user.find_by_id 
### I am able to verify the tuples in @mytesttbl
end 

在/view/mytest/index.rhtml中,我有像

这样的代码
<div id="mytesttable"> <%= render(:partial =>"mytesttbl", :object => @mytesttbl)%> </div> 

在/view/mytest/_mytesttbl.html.erb中。我有像

这样的代码
<tr>
 <td><%=mytestbl.name %></td>
<tr>

当我运行上面的代码时,我在_mytesttbl.html.erb上有错误,

undefined method 'name ' for #<Array:0xb6c971cc>

请帮忙。谢谢,

3 个答案:

答案 0 :(得分:2)

我猜这不是你的实际代码,因为它实际上不起作用。您的find正在返回一个数组。你想要循环遍历数组,或者,如果你知道它只包含一个对象(就像你实际上是通过一个唯一的id找到的那样),你可以只做mytesttbl.first来从中获取对象

答案 1 :(得分:1)

mytesttblarray。将view/mytest/index.rhtml更改为

<% @mytesttbl.each do |obj| %>
  <div id="mytesttable">
   <%= render(:partial =>"mytesttbl", :object => obj)%>
  </div>
<% end %>

编辑:此外,view/mytest/_mytesttbl.html.erb应该看起来像

<tr>
 <td><%= object.name %></td>
<tr>

答案 2 :(得分:0)

你错过了@ user.find_by_id的参数吗?通常当我想得到我的名字时:

控制器 @ user = User.find(params [:id])按特定ID查找用户。

视图

如果你想找到所有用户那么

控制器 @user = User.find(:all)

视图

User.find_by_id是redudant,因为默认情况下User.find按id查找。

相关问题