Graham S.
Graham S.

Reputation: 1540

Call custom action using RABL gem? Rails 4 and RABL

I have a custom action called search in my rails app that has two corresponding pages:

The form that corresponds to the search method looks like this:

= form_tag(listings_search_path) do
      .input-group.search-input-group
        %span#search-icon-addon.input-group-addon
          %span.glyphicon.glyphicon-search
        = text_field_tag :search, nil, :class => "form-control", :placeholder => "        Search for spaces.", "aria-describedby" => "search-icon-addon"
      #search-btns.col-md-12
        = button_tag :Search, :class => "btn btn-default search-btns", :value => "Search"
        = link_to 'listings/findnearme', :class => "btn btn-default search-btns" do
          %span.glyphicon.glyphicon-map-marker
          Find Near Me

And the route:

post 'listings/search'

When I submit the form for html response, it works perfectly fine and calls the search method as intended:

# search method
def search
  @listings = Listing.search(params[:search].downcase)

  respond_with(@listings)
end

In the top of my controller (outside of any actions), I have:

respond_to :xml, :json, :html

But when I append .json to the url, it calls the show action instead.

How would I get JSON response from the search method?


TL;DR:

Calling "localhost:3000/listings/search" goes to the search.html.haml and calls the correct action search.

Calling "localhost:3000/listings/search.json" does not go to search.json.rabl and calls the show action instead.

Rails, Y U no call custom action?

Upvotes: 0

Views: 108

Answers (1)

John Naegle
John Naegle

Reputation: 8247

I suspect you either need to add a (:.format) as an optional parameter to your route, or set the request type header. You can try this in jQuery to invoke the JSON action:

$.ajax({url: '/listings/search', dataType: 'JSON', method: 'GET'})

Basically, the request type is not being picked up from .json and you either need to make the proper request type or set it via the route.

Upvotes: 1

Related Questions