devoutsalsa
devoutsalsa

Reputation: 1200

Refactoring link in Rails 3.2.12

Refactoring an ugly URL

I link from a job to a new job application, but the URL generated for the application feels kind of messy and I'm wondering if there's a way to clean it up.

Is there a way to go from this not so pretty URL?:

http://localhost:3000/applications/new?application%5Bjob_id%5D=1

To this cleaner one?:

http://localhost:3000/applications/new

Thanks in advance!


The code:

Jobs controller:

def show
  @job = Job.find(params[:id])
end

Job show:

<%= link_to "New Application", new_application_path(:application => { :job_id => @job.id }) %>

Application controller

def new
  @application = Application.new(params[:application])
end

New Application

<%= form_for @application do |f| %>

  <%= f.hidden_field :job_id, :value => @application.job_id %>

  <%= f.label :email %>:
  <%= f.text_field :email %>

  <br />

  <%= f.submit "Submit" %>

<% end %>

EDIT

(added rake routes and routes.rb)

Rake routes

    applications GET    /applications(.:format)          applications#index
                 POST   /applications(.:format)          applications#create
 new_application GET    /applications/new(.:format)      applications#new
edit_application GET    /applications/:id/edit(.:format) applications#edit
     application GET    /applications/:id(.:format)      applications#show
                 PUT    /applications/:id(.:format)      applications#update
                 DELETE /applications/:id(.:format)      applications#destroy
            jobs GET    /jobs(.:format)                  jobs#index
                 POST   /jobs(.:format)                  jobs#create
         new_job GET    /jobs/new(.:format)              jobs#new
        edit_job GET    /jobs/:id/edit(.:format)         jobs#edit
             job GET    /jobs/:id(.:format)              jobs#show
                 PUT    /jobs/:id(.:format)              jobs#update
                 DELETE /jobs/:id(.:format)              jobs#destroy

Routes.rb

resources :applications

resources :jobs

Upvotes: 3

Views: 163

Answers (1)

Rahul Tapali
Rahul Tapali

Reputation: 10147

If you don't want to use nested routes (I recommend to use nested routes). But there are many solution to solve problem. To avoid params in URL (i.e.) http://localhost:3000/applications/new?application%5Bjob_id%5D=1 to http://localhost:3000/applications/new. You need to use form in your show page instead of link. You can do as follows:

  <%= form_tag url_for(new_application_path) do %>
    <%= hidden_field_tag "application['job_id']", @job_id %> 
    <%= submit_tag "New application" %>
  <% end %>

Upvotes: 1

Related Questions