0

Im trying to add a hash to an array like this :

rejects = self.user.rejects
rejects << {name: self.originalname, reason: reason}

User rejects is an array. Here's the migration line :

t.string :rejects, array: true, default: []

But I get something like this as the output :

["{:name=>\"wallhaven-56800.jpg\", :reason=>\"Quality not good enough\"}"]

How can I fix this?

THpubs
  • 7,804
  • 16
  • 68
  • 143
  • It's a string; what do you *want* it to be? – Dave Newton Mar 29 '15 at 13:03
  • @DaveNewton To be a hash – THpubs Mar 29 '15 at 13:03
  • 1
    Then don't add it to a string? You see where you define it as a string? – Dave Newton Mar 29 '15 at 13:04
  • @DaveNewton Ah.. in the migration right? Actually, that's how we can define arrays in the migration. IS there a different way? – THpubs Mar 29 '15 at 13:22
  • @DaveNewton When I check the type of it like this `User.first.rejects.class` it returned `array` – THpubs Mar 29 '15 at 13:27
  • @DaveNewton What I need is an array of hashes. :-) – THpubs Mar 29 '15 at 13:31
  • 1
    Oh, also double-check that `<<` ends up doing what you need it to--I vaguely recall an issue with how attribute tracking works and the shift operators, but that was some time ago and it may be different now. Make sure to check. – Dave Newton Mar 29 '15 at 13:40
  • @DaveNewton I used `.push` instead of `<<`, still have the same problem! – THpubs Mar 29 '15 at 14:01
  • ... The two issues are not related. You've declared the variable an array of strings. If you want to serialize a hash, then declare the column as serialized. The `<<` v. `push` is a completely different (potential) issue; it used to be a "gotcha", I don't know if it is now or not. – Dave Newton Mar 29 '15 at 14:15
  • @DaveNewton I added serialize in the model. Still the same problem – THpubs Mar 29 '15 at 14:50
  • You need to show what, specifically, you have in your DB migration now (e.g., you don't want an array if you're serializing) *and* in your model. There are examples of serialization all over--I'd consider finding one of those examples, e.g., http://stackoverflow.com/q/6694432/438992, http://viget.com/extend/how-i-used-activerecord-serialize-with-a-custom-data-type, or whatever. – Dave Newton Mar 29 '15 at 14:55
  • what does `self.user.rejects` return. – Mohammad AbuShady Mar 29 '15 at 16:46

1 Answers1

0

I would try something like this:

rejects = []

#inside your loop:
the_hash = {}
the_hash[:name] = self.original_name
the_hash[:reason] = reason
rejects << the_hash

That may not be the most efficient, I'm sure you could get it all on one line even, but that is a good start.

Stephen
  • 337
  • 2
  • 7