I'm following this SO answer and so am trying to call this method I defined:
class IngredientsController < ApplicationController
...
def get_restaurant_id(menu_id)
Menu.find_by_id(menu_id).restaurant_id.to_i
end
through an AJAX call:
m_id = $('#dish_menu_id').val()
$.ajax "/ingredients/get_restaurant_id(" + m_id + ")"
I've defined my routes.rb as such:
resources :ingredients do
get :get_restaurant_id, on: :collection
end
But my console.log($.ajax "/ingredients/get_restaurant_id(" + m_id + ")")
displays this error message:
GET http://localhost:3000/ingredients/get_restaurant_id(1) 404 (Not Found)
I'm not sure what I'm doing wrong. Is there another way to pass the m_id
parameter through an AJAX call?
Ideally, I'd like to have the AJAX call return the integer value of the restaurant ID.
PS -- This is the alternative solution I've come up to my original SO post about a problem I was trying to overcome.
Edit 1
I now understand a little better as to what I'm doing with the GET/POST (I hope) so I redefined my method as such:
ingredients_controller.rb
def get_restaurant_id
Menu.find_by_id(params[:m_id]).restaurant_id
end
But I get a Template is missing
and 500 Internal Server Error
.
I get that there is no template for this. So is there any way I can have it just do a simply SQL query to get the restaurant ID and return it back to the Ajax call?
So my Ajax call looks like this now:
$.ajax "/ingredients/get_restaurant_id?m_id=" + m_id
Edit 2: Almost There
I changed my method to this:
def get_restaurant_id
menu_id = params[:m_id]
r_id = Menu.find_by_id(params[:m_id]).restaurant_id.to_s
render :json => r_id
end
And now in my Ajax I get an Object
that has the answer within the responseText
field but I can't seem to access it.
I've tried this:
r_id = $.ajax "/ingredients/get_restaurant_id?m_id=" + m_id
alert "After call to get_restaurant_id " + r_id.responseText
But get it as undefined
.
The Object
in my console log looks like this:
...
readyState: 4
responseText: "1"
setRequestHeader: function ( name, value ) {
...