I could use your helping creating a valid JSON object in Rails.
Here is an example of a valid JSON object that I'm using in the jQuery plugin: https://drew.tenderapp.com/kb/autosuggest-jquery-plugin
var data = {items: [
{value: "21", name: "Mick Jagger"},
{value: "43", name: "Johnny Storm"},
{value: "46", name: "Richard Hatch"},
{value: "54", name: "Kelly Slater"},
{value: "55", name: "Rudy Hamilton"},
{value: "79", name: "Michael Jordan"}]};
Within Rails I'm creating my object as follows:
#projects = Projects.all
#projectlist = Array.new
#projectlist << {
:items => #projects.map { |project|
{
:name => space.name,
:value => space.id
}
}
}
But this ends up outputting like so which ERRORs by the plugin:
[{"items":[{"value":74,"name":"XXXXXX"},{"value":71,"name":"XXXXXX"},{"value":70,"name":"XXXXXX"}]}]
Looks like there is a [] around the initial {} any idea why that's happening and how to build a valid JSON object?
Thanks!
Simply assign #projectlist to a Hash, like so:
EDIT After looking at the plugin's API, I've come to the conclusion that you need to convert your values to strings first:
#projects = Projects.all
#projectlist = {
:items => #projects.map { |project|
{
:name => space.name,
:value => space.id.to_s
}
}
}
Since you're initializing #projectlist to an Array and pushing the Hash onto it, you're getting those wrapping [] characters.
Related
I am developing in student tracking website in RoR. In model I have following code to build json
self.as_json
json = Jbuilder.new do |j|
j.courses student_courses do |course|
j.(course, :id, :name)
j.students students, :name
end
end.target!
puts json
return json
end
My controller code is
render json: {
courses: course.as_json,
}
and produces
{"courses":[
"{\"id\": 1,\"name\": \"english\",\"students\": [{\"name\": \"ALison\"},{\"name\": \"Robert\"}]
},{...}... ]"
instead of
"courses" : [
{
"id": 1,
"name": "english",
"students": [
{"name": "ALison"},
{"name": "Robert"}]
}, {..},...
]
It is adding escape character(/) before every double quotes. How can I solve this issue
Hey you can use this to generate as alternative
course.to_json(:include => { :students => { :only => :name } })
My HTML looks like:
<%= column_chart #data, stacked: true %>
In my controller I created the data field:
#values = WorkingMonth.select("date_end","workload").where(personal_id: #current_employee.personal_id)
#values.each do |data|
#data = [
{
name: "Available",
data: []
},
{
name: "Workload",
data:[[data.date_end.strftime("%B"),data.workload]]
}
]
end
My problem is in #values there are more than only one value but it shows me only the last one. How can I use each do with this data field?
Thanks in advance
UPDATE:
I've changed my data field like:
#data = #values.map do |value|
#data = [
{name: "Available", data: []},
{name: "Workload", data:[[value.date_end.strftime("%B"),value.workload]]}
]
end
After changing the result looks like:
Column Chart
You should use map instead of each since you want convert #values array:
#data = #values.map do |value|
[
{ name: "Available", data: [] },
{ name: "Workload", data: [[value.date_end.strftime("%B"),value.workload]] }
]
end
I changed the way to think and stopped using .each/.map do. I've used "group" and "DATE_TRUNC". The answer to my problem looks like:
#data = [{name: "Workload", data: WorkingMonth.where(personal_id: #current_employee.personal_id).group("DATE_TRUNC('Month', date_end)").sum(:workload)}]
I'm a pretty new Rails developer, I'm using Jbuilder to build my view in the following way:
[:aaa, :bbb, :ccc].each do |value|
json.value do |json| #<------ Here is my error!
json.partial! foo.send(value)
end
end
Everything works BUT the json.value, my response is the following (obviously):
[{
"value" => {...}
"value" => {...}
"value" => {...}
}]
I'd like to have this one instead:
[{
"aaa" => {...}
"bbb" => {...}
"ccc" => {...}
}]
Any ideas?
From the guide:
To define attribute and structure names dynamically, use the set!
method:
json.set! :author do
json.set! :name, 'David'
end
# => "author": { "name": "David" }
The solution is so:
[:aaa, :bbb, :ccc].each do |value|
json.set! value do |json|
json.partial! foo.send(value)
end
end
I started to learn how to use Grape. I have collection with a lot of attributes and want only some of them. I did something like this:
get :all_elements do
[
my_collection.each do |element|
{
id: element.id,
name: element.name
}
end
]
end
However this is not working. How can I create custom json array from collection?
Please try this code.
list = my_collection.map do |element|
{ :id => element.id,
:name => element.email
}
end
list.to_json
I tried to do this:
Things.order("name").group("category_name")
I was expecting the results to be something like this:
[
{
"category_name": "Cat1",
"things":
[
{ "name": "Cat1_Thing1" },
{ "name": "Cat1_Thing1" }
]
},
{
"category_name": "Cat2",
"things":
[
{ "name": "Cat2_Thing3" },
{ "name": "Cat2_Thing4" }
]
}
]
So I would have expected to get an array of "categories" each with an array of "items" which are within that category. Instead, it appears to give me a list of things, sorted by the field I grouped on.
Note: category_name is a column in the thing table.
Try something like
my_grouping = Category.includes(:things).
select("*").
group('categories.id, things.id').
order('name')
=> #<ActiveRecord::Relation [#<Category id: 1, name: "Oranges">, #<Category id: 2, name: "Apples">]>
Though, you'll still have to access the Thing objects via my_grouping.things, they'll already be at your hand, and you won't have to wait for the results. This is likely the sort of interaction you're looking for, vs. mapping them into an actual Array.
One option is to do the grouping in Rails (it returns a hash)
Things.order("name").group_by(&:category_name)
#=> {"cat1" => [thing1,thing2,..], "cat2" => [thing3,thing4,..],..}
ActiveRecord::Base#group performs a SQL GROUP BY. I think, but i'm not sure (depends on your db adapter) that as you don't specify any SELECT clause, you get the first record for each category.
To achieve what you want, there are different ways.
For instance, using #includes :
Category.includes(:things).map do |category|
{
category_name: category.name,
things: things.sort_by(&:name).map{|t| {name: t.name} }
}
end.to_json
Note that the standard (albeit often frowned upon) way to serialize models as json is to use (and override if need be) as_json and to_json. so you would have something along the lines of this :
class Category < ActiveRecord::Base
def as_json( options = {} )
defaults = { only: :name, root: false, include: {links: {only: :name}} }
super( defaults.merge(options) )
end
end
Use it like this :
Category.includes(:links).map(&:to_json)
EDIT
As category_name is only a column, you can do :
Thing.order( :category_name, :name ).sort_by( &:category_name ).map do |category, things|
{ category_name: category, things: things.map{|t| {name: t.name} } }
end.to_json
such thing could belong in the model :
def self.sorted_by_category
order( :category_name, :name ).sort_by( &:category_name ).map do |category, things|
{ category_name: category, things: things.map{|t| {name: t.name} } }
end
end
so you can do :
Thing.sorted_by_category.to_json
this way, you can even scope things further :
Thing.where( foo: :bar ).sorted_by_category.to_json