Ryan McGarvey Ryan McGarvey - 1 year ago 55
Ajax Question

Trouble defining custom route in Rails - all ajax requests are defaulting to the show route

I'm trying to do an ajax call from the client which aggregates and then returns a single random ad from the server.

client side ajax call

getRandomPerk: function()
return $.ajax({url: url + "/advertisements/get_random_ad.json", type: "GET",dataType: "json", error: this.handleAPIError});


resources :advertisements do
#collection do
# get :get_random_ad

member do
get :get_random_ad

controller advertisement_controller.rb

def get_random_ad
@advertisement = Advertisement.find_random_advertisement()

model advertisement.rb

def self.find_random_advertisement

#ids = Advertisement.select("SELECT id FROM advertisements")

(this is supposed to return a random one but I've got it returning a specific one for debug purposes)

Server log

[time:0.000] Started GET "/advertisements/get_random_ad.json" for at 2016-07-27 18:04:17 +0000
[time:0.200] Processing by AdvertisementsController#show as JSON
[time:0.201] Parameters: {"id"=>"get_random_ad"}
[time:0.207] Advertisement Load (0.1ms) SELECT advertisements.* FROM advertisements WHERE advertisements.id = 0 LIMIT 1
[time:0.208] Completed 404 Not Found in 5.9ms
ActiveRecord::RecordNotFound (Couldn't find Advertisement with id=get_random_ad):
app/controllers/advertisements_controller.rb:16:in show'

Why is the rails logger saying "processing by AdvertisementsController#show"? Shouldn't it say "processing by AdvertisementsController#get_random_ad"? Maybe this is a fundamental misunderstanding on my part, but I thought that if you defined a new route in the routes.rb file then it would process all requests to that URL.

Answer Source

Since you're not using the #show action, you can use the only or except arguments. something like this should work:

   resources :advertisements, except: [:show] do
     member do
       get :get_random_ad

However, if you're only using :get_random_ad, you can omit the resource and instead use

get :random_ad, to: 'advertisements#get_random_ad', as: :random_ad
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download