I’m getting ‘undefined method `crop’ for {“crop”=>”Carrots”, “amount”=>12.15}:BSON::OrderedHash’ with following view:
%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?' }
The model is as below:
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
Data from shell as below:
> 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 } ] }
It looks like
harvested_cropsis an array of Hash objects, each containing two keys,"crop"and"amount". There’s nocropmethod on the standard Hash object; instead, you use the [] operator, just like an array, to access the contents. So try: