Pedro Souza
Pedro Souza

Reputation: 337

How set url in Javascript (js.erb) with Ruby?

I have this

route:

put :sort, :path => 'activities/sort', :controller => 'activities'

JS:

url: '/activities/sort',

I want to convert to this (without use controller name or :as attribute):

url: <%= :action => 'sort' %>, 

or the same href of something like this:

<%= link_to "Order by name",
         :sort,
         :method => :put %>

Upvotes: 0

Views: 332

Answers (2)

Syed Aslam
Syed Aslam

Reputation: 8807

You would've defined routes like this resources :activities in routes.rb which will give you seven RESTful routes for free. However, You are not limited to the seven routes that RESTful routing creates by default. If you like, you may add additional routes that apply to the collection or individual members of the collection.

resources :activities do
  collection do
    get 'sort_by_attr'
  end
end

Or

resources :activities do
  get 'sort_by_attr', :on => :collection
end

You can specify a name for any route using the :as option as in:

resources :activities do
  get 'sort_by_attr', :on => :collection, :as => :sort
end

which will give you sort_activities_path and sort_activities_url. Read more about Rails Routing from the Outside In.

EDIT:

If you just pass in :action parameter to link_to it would try to find that route in the current controller and render that action. Although not recommended, you can try defining a generic route to match any url like this:

match ':controller/:action'

Upvotes: 1

Michael
Michael

Reputation: 548

You should write in routes this url. Like:

config/routes.rb

match 'activities/sort_by_attr' => 'activities#sort', :as => :sort_by_attr

then write

url: <%= sort_by_attr_path %>, 

Upvotes: 2

Related Questions