ruby - Saving my rails object from an array of values sourced form a csv -


i'm trying update attributes via csv upload.

my method looks this:

def upload_csv   csv.parse(params[:file].read, headers: true) |row|     foo = foo.find_by_id(row.to_hash["id"])     row.to_hash.each |v|        if foo.new.has_attribute?(v[0]) && v[0] != "id"          foo.update_attributes()        end      end   end end 

when jumps want update attributes, i'm getting array looks this:

["bar", "22"] 

how can save value foo object?

ok, reading you're code i'm concluding problem have csv may contain fields not in model:

def upload_csv   excluded = %w/id created_at updated_at/   csv.new( params[:file], headers: true) |row|     rh = row.to_hash     foo = foo.find_by id: rh['id']     foo.update! rh.slice(*foo.attribute_names).except(*excluded)   end end 

note i'm assuming params[:file] uploaded file form, in case it's io object, , can passed csv.new directly (no need read memory , pass csv.parse).


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -