Rails JSON using RABL, showing parent attribute? - json

I have the following RABL file in my Rails 3.2 application:
collection #results.limit(5)
attributes :date, :client_id
child :client do
attributes :Surname
end
child :animal do
attributes :AnimalName
end
I would like to add the name of the user that the result belongs to. Everything I have read in the RABL documentation seem to suggest that only child and node are available.
How could I get a parents attribute within the above code? Just doing the following returns NULL, obviously!
child :animal do
attributes :AnimalName
end
Is this possible?
Current JSON output:
{
date: "2013-06-25T19:36:11+01:00",
client_id: 88172,
client: {
Surname: "Strange"
},
animal: {
AnimalName: "Ria"
}
},
Desired output:
{
date: "2013-06-25T19:36:11+01:00",
client_id: 882372,
client: {
Surname: "Summer"
},
animal: {
AnimalName: "Ria"
},
user: {
UserName: "Danny"
}
},

You can add a custom node that adds in the user data:
collection #results.limit(5)
attributes :date, :client_id
node :user do |report|
partial('users/show', :object => report.user)
end
This is assuming that you want the whole user/show template.
If you just want the name key/value:
node :user do |report|
{ :name => report.user.name }
end

Related

Sequelize create with associations

I have been trying to define a relationship between 3 tables and then create them all in one create function. For some reason, while creating the 3 models, the linking IDs (foreign keys) are undefined and are not passing on. Here are the associations:
Person.js:
models.person.Lead = models.person.hasMany(models.lead, {
onDelete: "CASCADE",
foreignKey: "person_id"
});
Lead.js:
models.lead.Person = models.lead.belongsTo(models.person, {foreignKey: 'person_id'});
models.lead.Sealant_customer = models.lead.hasOne(models.sealant_customer, {
onDelete: "CASCADE",
foreignKey: 'lead_id'
})
sealantCustomer.js:
models.sealant_customer.Lead = models.sealant_customer.belongsTo(models.lead);
The build function:
let sealantCustomer = models.sealant_customer.build({
address: body.address,
city: body.city,
roof_size: body.roofSize,
last_sealed: body.lastSealed,
existingSealant: body.existingSealant,
leaks_freq: body.leaksFrequency,
floor: body.floor,
elevator: body.elevator,
panels: body.panels,
home_type: body.homeType,
urgency: body.urgency,
next_step: body.nextStep,
more_info: body.moreInfo,
lead: {
site,
url: body.url,
date,
ip: body.ip,
person: {
name: body.name,
email: body.email,
phone: body.phone,
date,
city: body.city ? body.city : undefined,
address: body.address ? body.address : undefined,
}
}
}, {
include: [{
model: models.lead,
association: models.sealant_customer.Lead,
include: [{
model: models.person,
association: models.lead.Person
}]
}]
})
The outputted object is good except for the fact that lead_id and person_id are nulls (Each model has its own ID, but not the associated model's id). I also should note there are no validation errors and the data is good.
The library has a bug in the build function as far as I can tell. Same syntax with create worked perfectly.
In Sequelize v6, the association identifier in the include section is not valid. Otherwise, this build function should properly work.

How to return json using mongoid

I have a model:
class Client
include Mongoid::Document
field :name, type: String
field :age, type: Integer
index({ name: 1 }, { unique: true })
def self.list
self.all.as_json
end
end
When I call Client.list I get the following:
[{"client"=>{"_id"=>{"$oid"=>"58e91ccb9509d36cbaa8c79b"}, "name"=>"mark", "age"=>30}}]
What I am after is:
[{"_id"=>{"$oid"=>"58e91ccb9509d36cbaa8c79b"}, "name"=>"mark", "age"=>30}]
Which version of mongoid are you using ?
Check the documentation at:
https://docs.mongodb.com/ruby-driver/master/tutorials/6.1.0/mongoid-installation/
You can disable the include_root_in_json to remove the model name of the output json.
Can you try this solution?

Parse object to attribute-value with hamlc

I am using CoffeeScript and HAML. I have objects list:
{
title: "Title"
url: "http://example.com"
image_url: "img.png"
attributes: {
target: '_blank'
}
}
{
// ...
}
And I have a template:
- for item in #model.data
%a.menu-item{"href": item.url}
Can I somehow parse "attributes" if it is exists and add to %a.menu-item element to get <a href="[item.ur]" target="_blank">
If you want to merge all attributes from your hash, this should work:
%a.menu-item{item['attributes'], "href" => item['url']}
To conditionally include a tag element, use defined? The trick is in the ternery - setting the attribute value to nil will remove it. (https://gist.github.com/orioltf/3145400)
As an example (trying to mock up your situation with some quick ruby code)
- _h1 = {'title' => 'Title', 'url' => "http://example.com", 'image_url'=> "img.png", 'attributes'=> {'target'=> '_blank'}}
- _h2 = {'title' => 'Title2', 'url' => "http://example2.com", 'image_url'=> "img2.png"}
- $data_list = [_h1, _h2]
- class Model; def data() $data_list end end
- #model = Model.new
- for item in #model.data
%a.menu-item{:href => item['url'],
:target => (defined? item['attributes']['target']) ? item['attributes']['target'] : nil}
Note here that I am using hash accessors. Depending on your your objects are set up, what framework you are using, you may use what i did, item.url, item.get('url'), etc.
You can test it out with haml test.haml test.html
Hope that gets you started.

Display child element along with Parent in Rabl

I created rails-api application with rabl as json builder template. My models are below
class Course < ActiveRecord::Base
belongs_to :department
end
class Department < ActiveRecord::Base
has_many :courses
end
I am return courses as json. My Course has Title and Credits and DepartmentId. My existing rabl is
collection #courses => :courses
attributes :id, :Title, :Credits
But i need to include department name which is in the Department table. So my json is
{
courses:
{
course: {
id: 1045
Title: "Calculus"
Credits: 4
}-
}-
{
course: {
id: 1050
Title: "Chemistry"
Credits: 3
}-
}
}
}
I need as add department as next object after Credits. Is normal rails app, i can put course.department.Name in the html. but how in rabl? Please guidee me
I will suggest to add delegate in Course model
delegate :name, to: :department
then add
collection #courses => :courses
attributes :id, :Title, :Credits , :department_name

Prevent junction-table data from being added to json with sequelize

I've got the following models associated with sequelize.
Event hasMany Characters through characters_attending_boss
Boss hasMany Characters through characters_attending_boss
Characters hasMany Event through characters_attending_boss
Characters hasMany Boss through characters_attending_boss
These tables are successfully joined and I can retrieve data from them. But when I retrieve the JSON-results the name of the through model gets added to each object, like this:
{
id: 1
title: "title"
-confirmed_for: [ //Alias for Event -> Character
-{
id: 2
character_name: "name"
-confirmed_for_boss: [ // Alias for Boss -> Character
-{
id: 9
name: "name"
-character_attending_event: { // name of through-model
event_id: 1
char_id: 2
}
}
]
-character_attending_boss: { // name of through-model
event_id: 1
char_id: 2
}
}
So I'm looking for a way to hide these "character_attending_boss" segments if possible, preferably without altering the results post-fetch.
Is this possible?
Same issue is solved here: https://github.com/sequelize/sequelize/issues/2541
For me adding through: {attributes: []} to include block works well on Sequelize 2.0
Pass { joinTableAttributes: [] } to the query.