Rails 3 - Creating a JSON response to display Search Results - ruby-on-rails

I'm working to have Rails 3 respond with a JSON request which will then let the app output the search results with the jQuery template plugin...
For the plugin to work, it needs this type of structure:
[
{ title: "The Red Violin", url: "/adadad/123/ads", desc: "blah yada" },
{ title: "Eyes Wide Shut", url: "/adadad/123/ads", desc: "blah yada" },
{ title: "The Inheritance", url: "/adadad/123/ads", desc: "blah yada" }
]
In my Rails 3 controller, I'm getting the search results which come back as #searchresults, which contain either 0 , 1 , or more objects from the class searched.
My question is how to convert that to the above structure (JSON)...
Thank you!
Update
Forgot to mention. The front-end search page will need to work for multiple models which have different db columns. That's why I'd like to learn how to convert that to the above to normalize the results, and send back to the user.

I am not really sure what is the problem here, since you can always call ".to_json" on every instance or collection of instances or hash, etc.
You can use .select to limit the number of fields you need, ie:
Object.select(:title, :url, :desc).to_json
I am guessing that the #searchresults is ActiveRecord::Relation, so you probably can use:
#searchresults.select(:title, :url, :desc).to_json

Related

How to return friendly field names for zapier trigger (zapier developers)

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

In Power Automate, is there a way to filter on a Custom Field using DevOp's Send HTTP Request?

I'm trying to use Power Automate to return a custom work item in Azure DevOps using the "workitemsearch" API (via the "Send HTTP Request" action). Part of this will require me to filter based on the value of a Custom Field, however, I have not been able to get it to work. Here is a copy of my HTTP Request Body:
{
"searchText": "ValueToSearch",
"$skip": 0,
"$top": 1,
"filters": {
"System.TeamProject": ["MyProject"],
"System.AreaPath": ["MyAreaPath"],
"System.WorkItemType": ["MyCustomWorkItem"],
"Custom.RequestNumber": ["ValueToSearch"]
},
"$orderBy": [
{
"field": "system.id",
"sortOrder": "ASC"
}
],
"includeFacets": true
}
I have been able to get it to work by removing the Custom.RequestNumber": ["ValueToSearch"] but am hesitant to use that in case my ValueToSearch is found in other places like the comments of other work items.
Any help on this would be appreciated.
Cheers!
From WorkItemSearchResponse, we can see the facets (A dictionary storing an array of Filter object against each facet) only supports the following fields:
"System.TeamProject"
"System.WorkItemType"
"System.State":
"System.AssignedTo"
If you want to filter RequestNumber, you can just set it in the searchText as the following syntax:
"searchText": "RequestNumber:ValueToSearch"

Rails I18n, interpolation when we ask to receive a hash object

I have an issue with the interpolation of value in my strings, i ask for the related_links strings and i receive a hash with the title and the url.
this is my .yml
user:
subject: "New project created: %{title}"
related_links:
- title: Project Created
url: 'projects/%{id}'
When i ask for I18n.t("user.releated_links", id: xx) I get
{title: "Project Created", url: "projects/%{id}"}
DO any of you know how i can pass my parameters to related_links and it can interpolate the strings in the hash ?
I think you meant to use I18n.t("user.releated_links.url", id: xx).
You are missing the last key.
As a side note: Are you sure you want to generate URL from the localization files? Assuming those are links within your application, why don't you better use the rails helpers?
For anyone who still want the bellow output
{title: "Project Created", url: "projects/%{id}"}
Use deep_interpolate option
I18n.t("user.releated_links", deep_interpolation: true, id: xx)
Output => {title: "Project Created", url: "projects/xx"}

What is The default JSON specification used in RoR response?

I'm using RoR for a couple of time. But after read many json specification for example jsonapi.org and json-schema.org I have the next question: What is the default JSON specification used in RoR ?
Because when you render a json in RoR you get this for example:
post: {
id: 1,
title: 'Stackoverflow rised 1 billion of alien money',
description: 'blablabla'
}
Is it a good practice if I used the default response in RoR when I'm creating an API ?
One specific thing that may or may not be helpful...
One thing that bothers me about the default rendering of JSON w/ Rails is that it leaves the key names unquoted when serializing a Hash, which is (technically) not valid JSON. The way to fix this is to add
ActiveSupport::JSON.unquote_hash_key_identifiers = false
to a configuration file like environment.rb. Once you've done that, serializing
my_hash = { post: { id: 1, title: 'Stackoverflow rised 1 billion of alien money', description: 'blablabla' } }
to JSON would change to
post: {
"id": 1,
"title": 'Stackoverflow rised 1 billion of alien money',
"description": 'blablabla'
}
vs. what you have above without the quotes.

Creating json from array

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.

Resources