magic suggest returns POST 404 error - ruby-on-rails-4

I'm trying to get autocomplete working in my rails application using Magic Suggest.
I think this is the correct question: How can I get MagicSuggest to grab the JSON that is at the URL I give it?
This is the error that console returns when I type letters:
POST http://localhost:3000/search_foods 404 (Not Found) jquery.js:8706
Uncaught Could not reach server
Here's the magic suggest code:
input.magicSuggest({
data: "/foods/search/",
placeholder: "Search Foods...",
valueField:'idFood',
displayField:'foodName'
});
The Routes
resources :search_foods
The Controller and Action
class SearchFoodsController < ApplicationController
def index
render json: %['Crack', 'Cocain', 'Gorilla Test', 'Horse Test']
end
end
When I visit the /search_foods url directly I get
'Crack', 'Cocain', 'Gorilla Test', 'Horse Test'
as my code is designed to do.
I think the issue is in that MagicSuggest, by default, sends a POST request, although I'm not sure if that's entirely relevant:
You can pass the url from which the component will fetch its JSON data.Data will be fetched
* using a POST ajax request that will * include the entered text as 'query' parameter. The results
* fetched from the server can be:
* - an array of JSON objects (ex: [{id:...,name:...},{...}])
* - a string containing an array of JSON objects ready to be parsed (ex: "[{id:...,name:...},{...}]")
* - a JSON object whose data will be contained in the results property
* (ex: {results: [{id:...,name:...},{...}]

Try this:
input.magicSuggest({
data: "http://localhost:3000/search_foods",
placeholder: "Search Foods...",
valueField:'idFood',
displayField:'foodName'
});

The doc states that the component expects one of the following:
* - an array of JSON objects (ex: [{id:...,name:...},{...}])
* - a string containing an array of JSON objects ready to be parsed (ex: "[{id:...,name:...},{...}]")
* - a JSON object whose data will be contained in the results property
* (ex: {results: [{id:...,name:...},{...}]
When you visit /search_foods you get
'Crack', 'Cocain', 'Gorilla Test', 'Horse Test'
This does not fit any of the 3 supported cases.

My suspicions about the POST request was correct.
My friend helped out so that's why I was able to fix this.
This is what I did..
Eliminated the FoodSearch Controller, because that's not needed at all.
Created a search action in my Food Controller like so:
def search
render json: ['cocain', 'crack', 'gorilla testosterone']
end
Edited my routes to a POST request instead of a get *This was the key:
resources :foods do
collection do
post :search
end
end
--- Another option, as karlipoppins suggests, is to simply change the type of request that magicSuggest makes by including the method attribute like so:
input.magicSuggest({
method: 'get',
data: "/foods/search/",
placeholder: "Search Foods...",
valueField:'idFood',
displayField:'foodName'
});
Then I wouldn't need to change the route to post.
Added this path to the data attribute in the js
data: "/foods/search/"
This will be a huge help to anyone trying to get magicSuggest to work in rails. It's a pretty damn easy setup to be honest. That one bit and the JSON formatting was the only thing that was tripping me up here.

Related

Ruby convert Url parameters to array

I have this url encoded:
Started PUT "/path/thing/9812/close?status=close&shutdown_on=2018-12-05%2010%3A08%3A06&affected_external_id=15027&fqdns%5B0%5D=150.212.3.249"
which decoded is this:
"/path/thing/9812/close?status=close&shutdown_on=2018-12-05 10:08:06&affected_external_id=15027&fqdns[0]=150.212.3.249"
I get this parameters:
Parameters: {"status"=>"close", "shutdown_on"=>"2018-12-05 10:08:06", "affected_external_id"=>"15027", "fqdns"=>{"0"=>"150.212.3.249"}, "id"=>"9812"}
How can get fqdn as a array? on Rails 4
You should do the following:
params[:fqdns].to_a
Doing this, will produce the following:
{['0', '150.212.3.249', ...]}
If you wnat only the values, may you can try:
params[:fqdns].values
Doing this, will give you the following:
['150.212.3.249', ...]
But for this, you have to do it inside a ruby class, i strongly recommends you to do it inside your controller. Hope i can help.
UPDATE
After a recommends, you can do it with strong parameters, permiting the param fqdns as a hash (because you route receiving a hash):
def resource_params
params.permit(....., fqdns: {})
end
After this, you already have to execute the solutions above to get fqsnd as a array

django - Passing data to view without a form

I'm using Hansontable to allow users to create a matrix of input variables. How do I pass this matrix back to my views.py without it being part of the input form? I can add a form field for a 2-dimensional array, but I don't actually need it since the hansontable is creating the "input field".
I need to compute a set of results using the matrix before echoing it back to the user along with the results and storing it in a bd.
Any guidance is greatly appreciated.
Thanks.
To do pass any data to a backend without using a HTML form (without refreshing the page) you have to utilize AJAX methodologies/practice. Using jQuery you can do this like so:
$.ajax({
method: "POST",
url: "/some/url",
data: JSON.stringify(<handsontabledom>.getData())
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
Also note there is a tutorial on the Handson Tables documentation all about saving the data via a ajax request.
http://docs.handsontable.com/0.19.0/tutorial-load-and-save.html

How to handle empty respons of this.store.find('product', id) in emberjs?

In emberjs I have a /product/:product_id dynamic route which renders product template backed by model hook of ProductRoute and ProductController as expected.
this.store.find('product', id) uses RESTAdapter and gives me a response (which follows JSON Conventions for RESTAdapter) as : {product: {"id":"1","name":"prod1"}} and renders the template as expected when product is found. But when the product is empty (not found in database), I get the response as : {product: {}}. Now I am unable to figure out the way to intercept the response and check for empty dict, and give proper alert message (something like 'Product with given ID not found').
Note: The promise returned by this.store.find becomes an Ember Object of type product once resolved.
Ember's error message when no product is found : You must include anidin a hash passed to 'push'
Thanks.
An empty request is telling Ember-Data that the request was successful even though it wasn't. Your server should be responding with a 404 when the product isn't found, not an empty request. Otherwise, Ember-Data is going to assume that the empty object is the product.

Get server URL for Ember DS.Model Class

In using Ember Data for my models, there are some cases where I need to work around the data limitations and access other quasi-restful URLs on my server.
For example, I have a Feed object that records a stream of data. For accessing the models I have a RESTful endpoint:
/feeds/:feed_id
In order to start and stop recording a feed, I need to send a PATCH to a url like:
/feeds/:feed_id?update_action=start
Subsequently I can reload my model and see the changes reflected therein.
In this case, I need to access $.ajax and the URL is the same as the one Ember would use. However, I can't figure out how to eke this information out of Ember.
So far, the best I can do is:
DS.Model.reopen
rootForModel: Ember.computed( ->
#.store.adapterForType(#).serializer.rootForType(#.constructor)
)
pluralRootForModel: Ember.computed( ->
#.store.adapterForType(#).serializer.pluralize(#get("rootForModel"))
)
Such that for an instance of App.FeedItem I can do:
this.get("rootForModel") # feed_item
this.get("pluralRootForModel") # feed_items
And I'm guessing this would stay in sync with any settings made in the Adapter etc.
Subsequently, I can call like:
$.ajax
url: #get("pluralRootForModel") + "/" + #get("id")
data:
update_action: "start"
type: "PATCH"
Is this totally out in left field? Is there a more direct way to compose these URLs?
Another (related issue) is getting the underscored name for a given model.
App.MyModelController => my_model_controller
I've done something like:
Ember.Object.reopenClass
###*
* The underscored name for this.
* i.e. App.MyClass -> my_class
* From an instance, use this.constructor.underscored_class_name()
* #return {String} This classname, underscored.
###
underscored_class_name: ->
_.underscored("#{#}".replace(/^.*?\./g, ""))
Is this crazy? Are there any better ways?
Check out buildURL in DS.RESTAdapter.
If you want to use underscores in server paths and keys, check out DS.ActiveModelAdapter (and its default serializer, DS.ActiveModelSerializer). This adapter has its own implementation of buildURL.

understanding jquery ui autocomplete json

I am very new to programming and I am stumped with this problem.
I want to create am autocomplete textbox.
From what I see I would need to use json. However for the source of the json I need a url to a file script, and I do not quite get this part.
This is an example from http://jqueryui.com/demos/autocomplete/#option-source
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
Does it mean that whenever I type something in the autocomplete textbox it accesses the file in the url and the file script would change dynamically according to my input?
Also, I can only see some examples of the url file in php. Can it be done in Django? such as specifying a url as the source and link that url with a view outputting the data?
Whenever you type something in the autocomplete textbox it accesses the url to retrieve the array of data. (Use firebug or chrome developer tools while testing the demo to see the HttpRequests sent as you type)
From the documentation you linked:
"When a String is used, the Autocomplete plugin expects that string to
point to a URL resource that will return JSON data."
So yes, you can use Django as long as the URL returns JSON data.