检索数组中的对象

时间:2015-03-27 16:25:55

标签: ruby-on-rails ruby

我有一个包含以下对象的数组:

mobilephones = [[#<Phone id: 941, name: "CEO", representation_edavis_id: 172, phone_type_id: nil, number: "+12 3456789", sort_order: 13, remark: "mobile", created_at: "2015-03-05 13:27:24", updated_at: "2015-03-05 13:27:24", creator_id: nil, updater_id: nil, row_number: 941>],[#<Phone id: 946, name: "CFO", representation_edavis_id: 172, phone_type_id: nil, number: "+12 3456789", sort_order: 6, remark: "mobile", created_at: "2015-03-05 13:27:24", updated_at: "2015-03-05 13:27:24", creator_id: nil, updater_id: nil, row_number: 946>]]

如何检索数组中所有对象的名称和数字属性?


我认为通常它应该按照建议的方式工作,但在我的上下文中,在Rails应用程序中,我收到此错误消息:

undefined method `name' for #<Array:0x421c188>

在视图_show.html.haml中:

 ActionView::Template::Error (undefined method `name' for #<Array:0x421c188>):
    67: - list_mobilephones(r)
    68: - @mobilephones.each do |phone|
    69:   %tr
    70:     %td= phone.name
    71:     %td= "#{phone.number} #{phone.remark}"     
    72:

在application_helper.rb中:

  def list_mobilephones(rep)   
    @mobilephones = []
    rep.phones.each do |phone|     
      @mobilephones << [phone] if phone.remark == "mobile"     
      @mobilephones   
    end 
  end

2 个答案:

答案 0 :(得分:2)

如果你使用flatten

,在你的具体情况下就足够了
@mobilephones.flatten.each do |phone|
  -# some more code

根据变量的用法,您还可以避免构建嵌套数组。如果你只是在这个地方使用它,试试这个

def list_mobilephones(rep)   
  @mobilephones = []
  rep.phones.each do |phone|     
    @mobilephones << phone if phone.remark == "mobile"     
    @mobilephones   
  end 
end

答案 1 :(得分:0)

您只需遍历数组并访问对象信息,如下所示:

mobilephones.flatten.each do |obj|
  puts "name: #{obj.name}, phone_number: #{obj.phone_number}"
end