how to create a custom json from raw data (database data) - ruby-on-rails

I have create a show method in tour controller and want to render the data from the database into json format.
This the definition of the tour controller
class ToursController < ApplicationController
respond_to :json
def show
#tourcategory = Tourcategory.find(params[:id])
#tours= #tourcategory.tours
#tourcategories = Tourcategory.all
render :layout => false
end
end
This is the definition of the show.html.haml view
%h3 Tour for #{#tourcategory.title}
= #tours.to_json
The output of this code is following:
[{"content":"dscfds","created_at":"2015-12-12T09:48:32Z","elementid":"test1","id":8,"jobid":2,"next_button_title":"next","priority":23,"title":"test1","updated_at":"2015-12-12T09:48:32Z"}]
But i just want to render the data in this kind of json format, following:
var tour = {
id: "tour",
steps: [
{
title: "abc",
content: "Click this Button.",
target: "#abc",
placement: "bottom",
showNextButton: false,
skipIfNoElement : true
},

It's not clear what you're trying to achieve but it seems to me that you want to extract certain attributes from your #tours and group them as an array, if that's the case you can do something like this:
(list all the attributes you want inside t.attributes.slice())
tour = { id: "tour", steps: #tours.map { |t| t.attributes.slice("title", "content", "target") } }
and if you want to convert your keys from snake (underscore) to camel format:
tour = {
id: "tour",
steps: #tours.map {|t| t.attributes.slice("title", "content").map {|k,v| [k.camelize(:lower), v]}.to_h}
}

Related

Structure json inside controller

I need to do a json structure like this, but with more than 1 items:
charge = {
items: [{
name: "Product A",
value: 1000,
amount: 2
}]
}
I have an #items that is #items.pluck(:name, :price)
And I'm trying to create my json like this:
charge = {
items: [{
#items.each do |item|
'name:' = item.name,
'value:' = item.price,
'amount:' = 2
end
}]
}
And return this error:
SyntaxError in CoursesController#qualquer
syntax error, unexpected '=', expecting keyword_end
'name:' = item.name,
How i do this structure?
There are two things I see wrong. First, you're using "=" operator to set a Ruby Hash value. That's not correct, as Ruby hashes use symbols or strings. So your hash values will need to look like this:
{ "may_hash_key" => my.has_value }
or
{ my_hash_key: my.hash_value }
or
{ :may_hash_key => my.has_value }
Take your pick.
Additionally, if you are rendering JSON from your controller action, you can do something like this:
def index
# presumably some setup code
charge = {
items: #items.map do |item| {
name: item.name,
value: item.price,
amount: 2
} end
}
render json: charge
end
If you are not rendering JSON from your controller action, what you can do is set #charge and interact with it as a Ruby hash in your view instead.

Get the JSON representation of a model and an association

A QuestionTag belongs_to a Tag.
I want to get the JSON representation of a QuestionTag, and some information from the Tag it belongs to. What is the correct Rails-Activerecord query to get me this structure from a controller action?
{
question_id: 1,
name: "PHP",
description: "A programming language for monkeys."
}
Here are the tables:
QuestionTag
question_id
tag_id
Tag
name
description
In you controller, when you send back the response in JSON format, you can do something like following:
respond_to do |format|
format.json do
render :json => #tag.to_json(:include => { :question_tag => { :only => :question_id } })
end
end
Now, it will send response in the following format. It will send only question_id form QuestionTag table.
{
name: "name",
description: "description",
question_id: 0
}

Render only Items with a specific id

I render my Item's via <%= render #items%>
I added a migration AddCatIdToItems cat_id:string
Cat_id's: testA, testB, testC.
how can I render only items with the specific id testA?
e.g.: <&= #items.where(:cat_id => '1')&>
I use a seed file to populate the Item's. e.g.:
Tag.create([
{ name: 'example' },
{ name: 'example2' },
{ name: 'example3' }
])
How can i pass the cat_id into that?
is { name: 'example', cat_id:1 } working?
I am not sure what you are asking for. But I guess this is what you want
#items = Item.where("cat_id LIKE '%testA%'")
If you want to select all the items that have a specific cat_id, then
#items = Item.where(:cat_id => 'testA')

RABL: JSON objects without root key

I have this rabl template:
object #photo
attributes :id
child :comments do
attributes :id, :body
end
Which gives me this JSON response:
{
photo: {
id: 1,
comments: [
{
comment: {
id: 1,
body: 'some comment'
}
},
{
comment: {
id: 2,
body: 'another comment'
}
}
]
}
}
But I want it to look like this:
{
id: 1,
comments: [
{
id: 1,
body: 'some comment'
},
{
id: 2,
body: 'another comment'
}
]
}
Why does rabl wrap each element in the array with an extra object called comment. In this way when I access the collection in javascript I have to write:
var comment = image.comments[0].comment
instead of:
var comment = image.comments[0]
I know that if I include :comments in the attributes list for the #photo object it works the way I want, but when I want another level of nested associations for each comment object, there isn't a way to handle that besides using child, but that gives me the JSON response that I don't want.
Maybe I'm just misunderstanding the whole thing -- can someone explain or help? Thanks!
Got it!
Create a new file in config/initializers/rabl_config.rb:
Rabl.configure do |config|
config.include_json_root = false
config.include_child_root = false
end

Problem building JSON file

want to get all db entries by a specific hash and return it as json. I use the following code:
#tasks = Task.find_all_by_hash(params[:hash])
respond_to do |format|
format.json { render :json => #tasks }
end
now i have the problem that my json file isn't correct. it has the following output:
[
{
task: {
hash: "9dfca619f00f5488785f6b74ad1b590beefaee7a88c04884bf197e7679f3"
id: 4
created_at: "2010-12-16T09:09:51Z"
updated_at: "2010-12-16T09:14:10Z"
done: true
name: "Hallo"
}
},
{
task: {
hash: "9dfca619f00f5488785f6b74ad1b590beefaee7a88c04884bf197e7679f3"
id: 5
created_at: "2010-12-16T09:12:37Z"
updated_at: "2010-12-16T09:12:37Z"
done: true
name: "Test"
}
},
...
]
but actually i want it like this:
{ tasks: [
{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"Check out my content, this is loaded via ajax and parsed with JSON","author":"Ryan Coughlin"},
{"id":"2","date_added":"0000-00-00 00:00:00","post_content":"More content, loaded. Lets try to add a form in and post via ajax and append the new data","author":"Billy Bob"}
]}
any advice? thank you!
Try collecting the task alone to an array and create a json object using that. Some thing like
#tasks = Task.find_all_by_hash(params[:hash])
a = []
#tasks.each do |t|
a << t[:task]
end
b = {:tasks => a}
respond_to do |format|
format.json { render :json => b }
end

Resources