Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails nested routes with has_one association

I have two models:

Reservation:

class Reservation < ActiveRecord::Base
  has_one :car_emission
end

CarEmission:

class CarEmission < ActiveRecord::Base
  belongs_to :reservation
end

and following routes:

resources :reservations do 
  resources :car_emissions
end

Now when I want to create new car_emission i must visit url like this:

http://localhost:3000/reservations/1/car_emissions/new

and when i want to edit I must visit:

http://localhost:3000/reservations/1/car_emissions/1/edit

Is there anyway to change routes that my car_emission edit link will look like this:

http://localhost:3000/reservations/1/car_emission
like image 392
Mateusz Urbański Avatar asked May 07 '14 05:05

Mateusz Urbański


People also ask

What are nested routes in Rails?

In a nested route, the belongs_to (child) association is always nested under the has_many (parent) association. The first step is to add the nested routes like so: In the above Rails router example, the 'index' and 'show' routes are the only nested routes listed (additional or other resources can be added).

What is the difference between resources and resource in Rails?

Difference between singular resource and resources in Rails routes. So far, we have been using resources to declare a resource. Rails also lets us declare a singular version of it using resource. Rails recommends us to use singular resource when we do not have an identifier.

How do routes work in Ruby on Rails?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.


1 Answers

You want to do several things:

1. Create singular resource
2. Change the `edit` path for your controller

Singular Resource

As suggested by @sreekanthGS, you'll firstly be best creating a singular resource. This works in the same way as the resources method, except it treats your route as a single record; doing away with the index route etc:

#config/routes.rb
resources :reservations do
    resource :car_emission # -> localhost:3000/reservations/1/car_emission
end

Edit

This will create a set of RESTful routes for your car_emission , but it will still take you to the car_emissions#show action when you hit the "naked" link

You'll be best doing this:

#config/routes.rb
resources :reservations do
    resource :car_emission, except: :show, path_names: { edit: "" }
end

This will take you to the edit action when you hit the "naked" link

like image 176
Richard Peck Avatar answered Nov 14 '22 21:11

Richard Peck