Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 751
overtone Avatar asked Feb 25 '26 05:02

overtone


1 Answers

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'])
like image 95
BitOfUniverse Avatar answered Mar 03 '26 02:03

BitOfUniverse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!