overtone
overtone

Reputation: 1093

active record to hash inside itself

So this is a bit of a silly one and is more lack of programming knowledge rather than anything ruby or rails specific.

If i wanted to turn an ordinary class into hash its not so bad. I already have one:

class CustomRequest
  require 'json'
  require 'net/http'
  attr_accessor :url, :depth, :status

  def initialize(url,depth)
    @url = url
    @depth = depth
  end

  def make_me_hash_and_send

    @myReq = {:url => @url, :depth =>@depth}
    myJsonReq = @myReq
    puts myJsonReq

    res = Net::HTTP.post_form(URI.parse('http://127.0.0.1:3008/user_requests/add.json'),
    myJsonReq)

  end
end

Simply generates the hash from the internal variables that are passed in the constructor. I want to do the same for active record but the abstractness of it isn't making it easy.

Lets say I have this class

def  turn_my_insides_to_hash
#How do I take the actual record variables 
# nd generate a hash from them.
#Is it something like

@myHash = {:myString = self.myString
  :myInt => self.myInt }

end

I may be looking at this the wrong way. I know Outside of the class I could simply say

@x = Result.find(passed_id).to_hash

and then do what I want to it. But I would rather call something liks

@x = Result.send

(which turns the result's variables into hash and sends them) I already have the send part, just need to know how to turn variables into hash from inside class.

Upvotes: 2

Views: 8555

Answers (2)

David Clavijo
David Clavijo

Reputation: 387

record.serializable_hash

http://api.rubyonrails.org/v4.0.12/classes/ActiveModel/Serialization.html#method-i-serializable_hash

I write something more because SO ask me to do so.

Upvotes: 4

BitOfUniverse
BitOfUniverse

Reputation: 6021

You could try use JSON instead of YAML:

Result.find(passed_id).to_json

or

Result.find(passed_id).attributes.to_json

also you can use options like :except and :only for to_json method.

Result.find(passed_id).attributes.to_json(:only => ['status', 'message'])

Upvotes: 5

Related Questions