2012-09-30 59 views
0

我收到{「crop」=>「Carrots」,「amount」=> 12.15}的'undefined method crop':BSON :: OrderedHash'with following view:在HAML/Rails中使用嵌套數組的問題

%table 
    %tr 
    %th Date of Harvest 
    %th Crops 
    %th Photo 
    %th 
    %th 
    %th 
    %th 

    - @harvests.each do |harvest| 
    %tr 
     %td= harvest.created_at 
     %td 
     - harvest.harvested_crops.each do |harvested_crop| 
      %tr 
      %td= harvested_crop.crop 
      %td= harvested_crop.amount 
     %td 
     %td= harvest.photo 
     %td= link_to 'Show', harvest 
     %td= link_to 'Edit', edit_harvest_path(harvest) 
     %td= link_to 'Destroy', harvest, method: :delete, data: { confirm: 'Are you sure?' } 

的模型是如下:

class Harvest 

     include MongoMapper::Document 


     #references 
     key :photo,    String #photo of combined harvest (many crops) 
     key :harvested_crops, Array 
     key :user_id,   ObjectId 

     timestamps! 

     #Validations 
     validates_presence_of :harvested_crops 
end 

從殼如下數據:

> db.harvests.find() 
{ "_id" : ObjectId("5067846437bca62bccc3729d"), "user_id" : "5067844537bca62bccc3729b", "photo" : "mybumpercrop.jpg", "harvested_crops" : [  { "crop" : "Carrots",  "amount" : 12.15 },  { "crop" : "Apples", "amount" : 32.55 },  { "crop" : "Potatoes", "amount" : 12.44 },  { "crop" : "Spinach",  "amount" : 1.23 } ] } 
{ "_id" : ObjectId("5067846f37bca62bccc3729e"), "user_id" : "5067844637bca62bccc3729c", "photo" : "carrotsnspuds.jpg", "harvested_crops" : [ { "crop" : "Carrots",  "amount" : 1112.15 }, { "crop" : "Potatoes", "amount" : 3212.44 } ] } 

回答

1

它看起來像harvested_crops是哈的陣列sh對象,每個對象包含兩個鍵,"crop""amount"。標準Hash對象上沒有crop方法;相反,使用[]運算符就像數組一樣訪問內容。所以請嘗試:

%td= harvested_crop["crop"] 
%td= harvested_crop["amount"] 
+0

完美,謝謝! –

+0

嗨dpassage,也許你也可以幫我在這一個: 被難住了一天,語法再次相關,我不能針對選擇結構中的這些相同的值: http:// stackoverflow.com/questions/12659064/rails-mongomapper-nested-array-in-haml-form-trouble –