I have a rails object, for example :
Book {id:1, name: "name1"}
Book {id:2, name: "name2"}
I use the DataTables and the best ajax data is get the object as an string array, without the columns name.
How can I change the Book.all to array of data without columns names
The expected results is like this
Thanks
{
"data": [
[
"Tiger Nixon",
"System Architect",
"Edinburgh",
"5421",
"2011/04/25",
"$320,800"
],
[
"Garrett Winters",
"Accountant",
"Tokyo",
"8422",
"2011/07/25",
"$170,750"
],
[
"Ashton Cox",
"Junior Technical Author",
"San Francisco",
"1562",
"2009/01/12",
"$86,000"
]
]
}
Use pluck method like below, then you can get array of values.
Book.pluck(:title, :author)
To implement the DataTables in Rails.
Use this gem jquery-datatables-rails Click Here
You have to get the data from the controller as rails object. And populate table your in the view. Finally trigger the DataTable function on that table like this
`
$('#yourTable').DataTable({
// ajax: ...,
// autoWidth: false,
// pagingType: 'full_numbers',
// processing: true,
// serverSide: true,
// Optional, if you want full pagination controls.
// Check dataTables documentation to learn more about available options.
// http://datatables.net/reference/option/pagingType
});
No need of conversion into String or JSON
Related
I am working on a Zapier integration for an online form builder. Each unique form for our users has lots of long, auto-generated field names.
We have a trigger called “New form entries”, which polls our server for form entries, and comes back like this:
[
{
"id": "6209aee326baa600224d822c",
"email_907058157108782": "test#test.com",
"phone_589083232390193": "12345",
},
{
"id": "61fd629f19408200225e1893",
"email_907058157108782": "test#test2.com",
"phone_589083232390193": "54321",
},
]
However, this results in end users seeing these really long, gross field names in the Zapier interface:
My question: how do I get Zapier to display friendly labels to the user, whilst using the unique field IDs behind the scenes?
I’m thinking of returning something like the following (each object represents a form entry, , but I need to know how to actually use “friendlyFieldName” and “value” in Zapier!-
[
{
// the id for the entry
"id": "62179ec5ab9daa0022df7d1d",
// the id for the first field entry
"text_576692390099896": {
// a friendly name and value for zapier
"friendlyFieldName": "What is your favourite colour?",
"value": "Blue"
}
}
]
Thank you :)
You can define output fields labels in outputFields. Here are the reference document that you can follow: Output Fields
I'm trying to translate aggregation from the MongoDB shell to ruby code that uses Mongoid as ODM.
I have some documents like this (very simplified example):
{
"name": "Foo",
"tags": ["tag1", "tag2", "tagN"]
},
{
"name": "Bar",
"tags": ["tagA", "tag2"]
},
...
Now I'd like to get all documents with the name field and the total number of tags for each.
In the MongoDB shell I can achieve it using aggregation framework like this:
db.documents.aggregate(
{$project: {name: 1, tags_count: {$size: $tags}}
)
And it will return:
[{"name": "Foo", "tags_count": 3},
{"name": "Bar", "tags_count": 2}]
Now the frustrating part, I'm trying to implement the same query inside a rails app using Mongoid as ODM.
The code looks like (using rails console):
Document.collection.aggregate(
[
{'$project': {name: 1, tags_count: {'$size': '$tags'}}}
]
).to_a
And it returns the next error:
Mongo::Error::OperationFailure: The argument to $size must be an Array, but was of type: EOO (17124)
My question is: How can I make Mongoid understand that $tags makes reference to the correct field? Or what I'm missing from the code?
Thanks
It looks like there is data which does not consistently have an array in the field. For this you can use $ifNull to place an empty array where none is found and thus return the $size as 0:
Document.collection.aggregate(
[
{'$project': {name: 1, tags_count: {'$size': { '$ifNull': [ '$tags', [] ] } } }}
]
).to_a
Alternately you could simply skip where the field is not present at all using $exists:
Document.collection.aggregate(
[
{'$match': { 'tags_count': { '$exists': true } } },
{'$project': {name: 1, tags_count: {'$size': '$tags'}}}
]
).to_a
But of course that will filter those documents from the selection, which may or may not be the desired effect.
["from": /topics/nursery-a, "is_background": false, "flag": 1, "data": {"msg_head_id":{"msg_head_id":7,"name":"Section","created_at":"2017-01-24 19:34:43"},"msg_title":"hello","message":{"msg_head_id":7,"doc_url":"","msg_title":"hello","created_at":"2017-02-24 10:11:07","message_id":225,"message":"welcome"},"user":{"user_id":57,"gcm_registration_id":"","name":"Iron","created_at":"2016-12-27 12:41:18","email":"info#mail.in"}}, "title": Smart , "collapse_key": do_not_collapse]
it's not a valid JSON. it should be start and close with { and }, remove [ and ], also quotation mark is missing. After these changes try this in http://json.parser.online.fr/
According to the official site, json is built on two structures -- which named dictionary and array in iOS.
So this json output isn't valid json. The value of a json key should be one of array/object(key value pairs)/number/string/boolean/null.
The from, title, collapse_key should boxed in "" to be a string.
And the json output should start and end with {} not [].
I'm converting model query results to json and send them to selection box with
MyModel.find(params[:id]).my_sub_models.map(&:attributes)
I'm displaying my_sub_model :name(s) in selection box. Thats ok.
Later i added a column(:label) to sub model and i want to display a combined text in selection box like :name-:label. So i created a method
def combined_name
self.name + "-" + self.label
end
How can i add combine_name for each item into my json now?
Any idea? Thanks
To include any methods on the model, use :methods.
my_model.to_json(:methods => :combined_name)
# => {"id": 1, "name": "My Name", "label": "Label",
"created_at": "2012/02/01", "combined_name": "My Name - Label"}
Reference: API Doc.
Update:
to_json method of ActiveRecord was deprecated after 2.3.8. You probably are using Rails 3. A similar question was asked sometime back here and the responses might help you here. Especially about the gem acts_as_api. Do check.
Have u tried collect?
MyModel.find(params[:id]).my_sub_models.collect { |sub_model| [ submodel.id, submodel.combined_name ] }
This way you will send only id and the name, that you will need for your select box.
I'm creating a Web application which is simple enough, I am able to leverage a lot of standard Ruby on Rails 3 functionality (adding and removing model elements etc.).
Now I want to dish out a REST service, which returns a hierarchy of elements in one stream.
For example, in the model I have:
ProductType, which defines which combinations of ComponentTypes are allowed. Example:gift basket which is defined as having several Wine bottles and 3 pieces of fruit.
ComponentTypes. Examples: fruit, wine bottles, etc.
Components: These are embodyments of ComponentTypes. Examples: Sauvignon blanc, Apple, Pear, etc.
Now I would like to provide a "menu" rest service, which displays a hierarchy of these. It should look something like this:
"menu": [
{ "name":"Gift basket", "description":"some description", "price": 0, "isDefaultSelected": false, "isMultiselect":false ,"isContainer":true, "children":[
{ "name":"Wine", "description":"", "price": 0, "isDefaultSelected": false, "isMultiselect":false ,"isContainer":true, "children":[
{ "name":"Sauvignon Blanc", "description":"...", "price": 170, "isDefaultSelected": true, "isMultiselect":false, "isContainer":false },
{ "name":"Merlot", "description":"...", "price": 170, "isDefaultSelected": false, "isMultiselect":false ,"isContainer":false }
]
},
{ "name":"Fruit", "description":"Fruits...", "price": 0, "isDefaultSelected": false, "isMultiselect":false ,"isContainer":true, "children":[
{ "name":"Apple", "description":"...", "price": 170, "isDefaultSelected": true, "isMultiselect":false ,"isContainer":false },
{ "name":"Pear", "description":"...", "price": 170, "isDefaultSelected": false, "isMultiselect":false ,"isContainer":false }
]
}
]
}
From this, the client is to create a menu, where the items that have the property "isMultiselect" are checkboxes. Some attributes are arguably redundant (isMultiselect could simply be on a higher part of the hierarchy), but we have a requirement for all of the elements to be identical.
So my question is whether I should create a new model to represent the objects that I want to have in our REST service or whether I can render the objects that I have in a way that conforms to the above JSON Schema.
It's a little unclear what 'menu' is. Is it just a list of ProductTypes? Are there multiple Menus?
As to the general question - yes, you should be able to use the existing resources defined for your JSON feed. If you need to customise the JSON feed (eg to include child resources), you can do so using the respond_with method:
respond_to :html, :json
def show
#product_types = ProductType.all
respond_with(#product_types, :include => [:component_types => :components])
end
I would suggest looking into the awesome_nested_set gem to see if you can represent your hierarchy that way. Basically you have to add 3 new columns to your existing model and you get all the standard tree support. Then you can add one or two simple routes to the related controller and you should be good to go.