Rails: how can I set a route for a method that does not require a parameter: id, but instead requires 2 request parameters

I have a list table with a listing model and the lists_controller class. I wrote a method that requires 2 parameters: latitude and longitude. He then retrieves the lists located around this coordinate for about 5 km. In lists_controller, this is the method I wrote:

def around lat = params[:latitude] long = params[:longitude] @surroundings = Listing.where("latitude = ? and longitude = ?", lat, long) end 

What I would like to do is set the URL in the routes.rb file, which, when the client browser is called, will provide latitude and longitude in the form of 2 parameters. No: the id parameter can be provided, because the client browser does not know the identifier, and, moreover, there can be no record in the database that exactly matches the coordinates. Remember that Im only looking to search lists around specific coordinates.

So how to write this in the routes file?

Here is the result of my rake routes command

  listings / listings#index GET /listings(.:format) listings#index POST /listings(.:format) listings#create new_listing GET /listings/new(.:format) listings#new edit_listing GET /listings/:id/edit(.:format) listings#edit listing GET /listings/:id(.:format) listings#show PUT /listings/:id(.:format) listings#update DELETE /listings/:id(.:format) listings#destroy /:controller(/:action(/:id))(.:format) :controller#:action 

And this is what the routes.rb file looks like:

 Businesses::Application.routes.draw do root to: 'listings#index', as: 'listings' resources :listings match ':controller(/:action(/:id))(.:format)' 

Here is what I was hoping to use as a url string from a client browser:

 http://localhost:3000/listings/around?latitude=XXX&longitude=XXXX 

Any help would be appreciated

+4
source share
2 answers

You basically are fine, the only question is how to create the actual URL. As I can see, you have 2 options:

  • Use only the paths that you already have:

     listings_path( :latitude => lat, :longitude => lng ) 

    This will work and generate a path similar to /listings?latitude=XXX&longitude=XXX

  • If you need a version of /listings/around?... you can add it like this:

     # routes.rb resources :listings do collection do get :around end end 

    Then you can make your url like this:

     around_listings_path( :latitude => lat, :longitude => lng ) 
+2
source

try setting the action "around" as a collection:

 resources :listings do get :around, :on => :collection end 

And in your opinion

 =link_to around_listings_path(:latitude => lat, :longitude => long) 
0
source

Source: https://habr.com/ru/post/1402057/


All Articles