0

我得到了 {"crop"=>"Carrots", "amount"=>12.15}:BSON::OrderedHash' 的“未定义方法 `crop”,视图如下:

%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

来自shell的数据如下:

> 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 } ] }
4

1 回答 1

1

它看起来像是harvested_crops一个 Hash 对象数组,每个对象包含两个键,"crop"并且"amount". crop标准的 Hash 对象没有方法;相反,您可以像数组一样使用 [] 运算符来访问内容。所以试试:

%td= harvested_crop["crop"]
%td= harvested_crop["amount"]
于 2012-09-30T01:24:49.587 回答