ruby on rails - Converting ActiveRecord results to json in transaction script -
I have seen many posts on this but none of the solutions is working for this application. I have a transaction script, CreateContact, which adds a successful object when added to the database:
Class CreateContact & lt; Here is my test code: 'Spec_helper' describes 'CreateContact' as it does (such as: 'transaction)' (CreateContact.new) "Create contact" contact = CreateContact.run ({: name = & Gt; 'contact1' ,: email = & gt; 'Me@email.com' ,: phoneNum = & gt; '1234567'}) Hopefully (contact.success?). Eq (true) is expected (contact.name). Eq ('contact1') is expected (contact.email). AEK ('me @ email') is expected (contact.phoneNum) AEC ('1234567') End End
I have tried several ways to parse one hash or JSN: contact. Separating the parachute hash in the content, adding the success object value to ".to_json" and "jeson peres", calling on the complete success object, and '.to_a.map' serializable_hash). I also tried to change the test code properties between '.property', '[: key]', and '[property'] 'formats. '[' Property ']' is the only one who returns anything, but it only gives "property" (instead of one value).
If I run tests, I can actually see ActiveRecord objects that have been successfully created, and some of these techniques will be parsed if I call them in binding. But when I try to apply them in the code, the tests still change the zero values. Can anyone see what I am doing wrong?
To change an ActiveRecord object to a JSON-like hash, you as_json
method:
hash = contact.as_json # = & gt; {"Id" = & gt; 1, "name" = & gt; "Contact1", ...}
You then hash ["attribute"]
to the content of hash. However, you will be able to call not hash [: attribute]
or hash.attribute
:
. Hash ["name"] # = & gt; "Contact1" hash [: name] # = & gt; Neil Hash Name # = & gt; NoMethodError: Undefined method for {} `name ':} hash
If you want to add that behavior to hash, you can create it with a hash:
hash2 = opencast New (contact .assigguson) hash2 ["name"] # = & gt; "Contact1" hash2 [: name] # = & gt; "Contact1" hash.name # = & gt; "Contact 1"
If you just need JSON as an actual string
, then use to_json
: < / P>
json = contact.to_json # = & gt; "{\" Id \ ": 1, \" name \ ": \" contact1 \ ", ...}"
Comments
Post a Comment