How can I read JSON sublevels with rails? - ruby-on-rails-3

I am new to rails and I am trying to read a JSON uri. I can read the information but I donĀ“t know how to access the sublevels of the json file. I am doing this:
resp = Net::HTTP.get_response(URI.parse(uri))
parsedresp = JSON.parse(resp.body)
I get as a answer the follow information:
{"success"=>true, "data"=>[{"id"=>1, "public_id"=>1, "company_id"=>60861, "user_id"=>{"value"=>74138, "name"=>"Daniel Galvao"}}]}
When I use parsedresp["data"] I get the information:
[{"id"=>1, "public_id"=>1, "company_id"=>60861, "user_id"=>{"value"=>74138, "name"=>"Daniel Galvao"}}]
My problem is that I don't know how to get the information "name"=>"Daniel Galvao" to store in the DB. Can someone help me? Thanks in advance!

The value of parsedresp["data"] is an array, so to get its value, you have to pass it an index ([0] for the first and only element):
parsedresp["data"][0]
#=> {"id"=>1, "public_id"=>1, "company_id"=>60861, "user_id"=>{"value"=>74138, "name"=>"Daniel Galvao"}}
To get the user data, pass this hash the user_id hash key:
parsedresp["data"][0]["user_id"]
#=> {"value"=>74138, "name"=>"Daniel Galvao"}
If you want to get the name of the user, then:
parsedresp["data"][0]["user_id"]["name"]
#=> "Daniel Galvao"

Related

Sorting out data from SQL in Rails

So I'm trying to get some specific data out of my database but I've searching online and can't find how to do this (probably because I'm searching for the wrong terms).
I start with getting all the participants with a specific id like this :
contributions = Participant.where(user_id: params[:id])
This will give me a json result like this :
0: {id_request: "1", user_id: "titivermeesch#gmail.com"}
1: {id_request: "2", user_id: "titivermeesch#gmail.com"}
So here I have all the requests (there is a Request class) that have that specific user_id.
Now I want to do this :
all = Request.where(id: id_request)
This obviously don't work but how would I get all those requests that have all those id's that come from the first database query?
So with the results above I should get Request 1 and 2, but how? Can anyone guide me?
How about
contributions = Participant.where(user_id: params[:id])
# Assuming the above is an active record query and id_request is a property of Participant
all = Request.where(id: contributions.map(&:id_request))
This is the equivalent of the SQL
select * from requests where id in (array_of_request_ids)
If You added associations in your model? it's very easy to retrieve the records
This should work:
Request.joins(:participants).where("participants.user_id = ?", params[:id])
Also you might want to read the following part (on joins)

JSONAPI Resources, need a filter for the last record

so I'm looking at creating a filter for a JSONAPI resource where I'll grab anything created within the last 10 minutes and return only one result if something's there.
Problem, when I call .last(1) on the returned records I get an error:
"exception": "undefined method `order' for #<Array:0x007fde4770bcf0>"
My non-breaking query is this:
records.where(user_id: user_id, updated_at: ten_minutes_ago..current_time)
Any help? I'd like to do this on the Rails-side rather than deal with a mangle of results (or no results) on our front-end. Thanks!
Okay, so the deal is this.
In order to grab only 1 record you'll probably have to overwrite/define your own paginator, like so:
paginator :none
I'd put it after your attributes and before your filters. Cool? Cool. Next, you can just do your basic Rails querying:
records.where(user_id: user_id, updated_at: ten_minutes_ago..current_time)
.order(id: :desc)
.limit(1)
You need to set your paginator or else the defaults or whatever you've defined will overwrite your limit query. Sweet. Easy.

"putting" a certain object to the screen from inside an array

I have an array, "templates".
puts templates
gives me the following output:
{"id"=>4, "subject"=>"invoice", "body"=>"dear sirs", "description"=>"banking", "groups"=>"123", 0=>4, 1=>"invoice", 2=>"dear sirs", 3=>"banking", 4=>"123"}
I would like to "put" a certain element e.g. "dear sirs". I have tried:
puts templates[2]
but this just returns nil. What is the correct way to do this?
You access "dear sirs" using the key that's associated with it, "body":
puts templates["body"]
Suppose if you have hash like this
#a = {"id"=>4, "subject"=>"invoice", "body"=>"dear sirs", "description"=>"banking", "groups"=>"123", 0=>4, 1=>"invoice", 2=>"dear sirs", 3=>"banking", 4=>"123"}
And if you want to get value of key name 'body', then you can get output like this,
puts #a['body'] //Output = dear sirs
puts #a['subject'] //Output = invoice
For more information for ruby hash Ruby Hash
If you want to get a hash value by numeric index then you can do templates.values[index]
e.g
templates.values[0] => 4
templates.values[1] => "invoice"
templates.values[2] => "dear sirs"
Note: My answer is based on strong assumptions that may not be true. I have provided steps to validate that.
In-case you are on older ruby version you need to do puts templates.inspect in-order to print a Hash. Therefore suggesting your variable templates is a String. Best way to verify:
templates.class
#=> returns Hash or String accordingly.
If it return String, you can proceed as follows:
Convert the String into Hash
hash = eval(templates)
#=> {"subject"=>"invoice", 0=>4, "description"=>"banking", 1=>"invoice", 2=>"dear sirs", "id"=>4, 3=>"banking", "body"=>"dear sirs", 4=>"123", "groups"=>"123"}
Now that its a Hash you can access any value using its key like:
hash[key]
#=> val
Example for your case:
hash[2]
#=> "dear sirs"

How to access data of query Comment.group('user').count

The query below in Rails console:
i = Comment.group('user_id').count
gives me output like this:
{1=>3, 2=>6, 3=>2, 4=>8}
where 1,2,3,4 are user ids and 3,6,2,8 are the count of the rows with these user ids. Please shed some light on me on how I can use these data. As i.count gives me total no.
I want to access these individual user row counts. Again, i[0].count or i[1].count gives me an error.
The expression gives you a Ruby Hash of key/value pairs, which you can access using the following:
i[1] # => 3
i[2] # => 6
... etc ...
You don't need to call count on them, the value of calling i[2] will be the count.
If I understand your question, you can access the hash with i[1] to get the comment count for the user with ID #1, instead of adding .count as you did in your example.

Rails3 Find Distinct gives result not object

I'm trying to select the User Id as a variable in the console however I keep ending up with:
[#<User id: 4>]
The find statement I have tried is:
userid = User.select('id').where('username = ?', 'uwZgf')
I've also tried with find_by_sql with same result.
What do I need to get the value out instead of the hash?
What you've got there is an array of one User object.
User.select(...).where(...).first.id
Would do the trick (you'd probably want to check the value returned by first before trying to call id on it.
You might find
User.find_by_username('foo').try(:id)
more readable.