I have a hash H which should contain various users as json. "users" list contains all users and every user object contains various user's details like name, age etc. I don't want to iterate over every user in the list and do user.as_json and then merge into the hash.
Is there a single line query which does this?
You can do this, in your action convert it to JSON by using to_json
#users = users.to_json
In the Javascript code, parse it using jQuery's $.parseJSON()
$.parseJSON(#users)
Related
I want to compare a param extracted from a link to the list of data present in column...
I am using pluck to generate a array of list(in controller) but not getting any success in comparing it
any method that I can fetch records in model and compare with param in controller or model
as passing controller instances in model seems inappropriate to me
Initially i am trying fetching and comparing in controller..
#abc=Group.pluck(:group_token)
what I tried to do before is defined group_fetch method in model and used it in controller to check condition but I was not able to compare param which comes frome url dynamically
def self.group_fetch
Group.find_by group_token: 'UuzsG7NMvYFzxwPDdYgLxJbF'
end
what will be the best way to fetch db column and compare it with the link param
You can use the exists? method which pretty much does what it says.
Group.exists?(group_token: params[:token])
You can use include? to check if the param is in the list. For example:
def your_method
list = Model.pluck(:attribute)
list.include?(params[:your_param])
end
i have two two models post, tags and i want to get post where some tags.
tag.rb
post_id integer 3
tags array {'v1', 'v2'}
when search in tag model work Tag.where('tag && array[['v1', 'v2']]')
but when add this in post not work Post.where('tags.tags && array[['v1', 'v2']]')
every post has one tag
The most direct/raw way to do this would be something like this:
Post.joins(:tags).where("ARRAY['v1', 'v2'] <# tags.tags")
Obligatory warning about injecting user-inputted values into strings sent to a database, for the WHERE clause.
I had a bit more complex sql-query which i decided to use plain sql rather than writing it with AR. I wrapped the sql-statement inside ActiveRecord::Base.connection.exec_query` .
The method basically looks like that:
def sc_agent
return ActiveRecord::Base.connection.exec_query("SQL").as_json
end
The serializer as_json gives me a json hash with json strings. So also id's are now strings
{"id":"123","age":"99"}
On standard queries where i use AR i receive nicely
formatted json with the correct types.
How can i retain the correct types of all the values when using the ConnectionAdapter directly? Thanks for everything!
Use find_by_sql method.
Example: Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date].
More info is here: http://api.rubyonrails.org/classes/ActiveRecord/Querying.html
I currently have a JSON response, fairly simple one. But I couldn't find a good guide or kicking off point for getting the JSON response and saving it within a model that I have e.g posts.
"Grab a JSON feed containing posts and save each one within the posts
table in rails"
Is there a simple way to do this with rails?
Any help is greatly appreciated.
Not a lot to work with...but let's assume the json string is represented by the variable json_str.
parsed = JSON.parse(json_str)
The parsed string should now essentially just be key value pairs like any other hash. To get the value, simply use the key.
parsed["some_key"]
Will return the value. To make your post from this, you can take the values you need and pass them in one by one, like so:
Post.create(some_value: parsed["some_key"], # etc)
Or, if all of your keys happen to share names with your attributes, you can pass the params all at once by saying:
post = Post.new(parsed)
and then calling:
post.save
Let me know if you have trouble.
I have a rails app which gets a response from World Weather Online API. I'm using the rest-client gem and the response is in JSON format.
I parse the response using:
parsed_response = JSON.parse(response)
Where parsed_response is obviously a hash.
The data I need are strings inside a hash inside an array inside a hash inside another array inside another hash inside another hash.
The inner-most nested hashes are inside ["hourly"], an array of 8 hashes, each with 20 keys, possessing string values of various weather parameters. Each of these hashes in the array is a different time of day (the forecast is three-hourly, 3*8 = 24hours).
So, for example, if I want the swell height in metres at 9pm, I find it with the following call:
#swell_height = parsed_data["data"]["weather"][0]["hourly"][7]["swellHeight_m"]
Where the 7th element in the array correspond to "time" => "2100"
While I can definitely work with this, I'm curious as to whether there is a more straightforward method of accessing my data, like if it was a database table, I could use active record, something like:
#swell_height = parsed_data.swellHeight_m.where(:time => "2100")
You may want to look at JSONPath. It does exactly what you need. Its syntax is very similar to XPath, but JSONPath works with JSON data (as obvious).
There is a Ruby implementation: https://github.com/joshbuddy/jsonpath
I personally use it in every project where I need to test JSON responses.