I cannot replace an Array with my Mongoid based model

63 views
Skip to first unread message

Matthew Hillsborough

unread,
Mar 31, 2014, 12:55:38 PM3/31/14
to mon...@googlegroups.com
I have a Mongoid based model in my Ruby on Rails application. 

Here's a slimmed down version of the model:

    module MLB
    class Roster
    include Mongoid::Document
    include Mongoid::Timestamps
    
    field :team_id
    field :season_year
    field :position_categories, type: Array
    
    index({team_id: 1})
    
    validates :team_id, presence: true
    validates :season_year, presence: true
    validates :position_categories, presence: true
    
    def self.parse!(entry)
                            // .. cut 
    
    obj = find_or_create_by(team_id: json_document['team_id'], season_year: json_document['season_year'])
    obj.team_id = json_document['team_id']
    obj.season_year = json_document['title'].match(/\d+/)[0].to_i
                        # PROBLEM HERE - new array will not overwrite existing array
    obj.position_categories = json_document['position_categories']
    
    obj.save
    end
        end


The problem I'm having is commented above. I can't just simply overwrite the existing array, position_categories, with the new one as depicted above. Do I need to empty it out first? Is there an easy way to just overwrite the entire array here? For what it's worth, I'm using Mongoid 4.

I've also tried doing the following with NO luck:

obj.position_categories = obj.position_categories || []

obj.position_categories.replace(json_document['position_categories'])


The original array just stays in place. I have to delete the document entirely and re-create it for the new position_categories to take place. Any ideas on what's going on here?



Reply all
Reply to author
Forward
0 new messages