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 the following routes:

resources :reservations do 
  resources :car_emissions
end

Now that I want to create a new car_emission, I have to visit the url, like this:

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

and when I want to edit, I have to visit:

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

Is there a way to change the routes along which my link to edit car_emission would look like this:

http://localhost:3000/reservations/1/car_emission
+4
source share
4 answers

You want to do a few things:

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

Unique resource

@sreekanthGS, , -, . , resources, , ; index ..:

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

Edit

RESTful car_emission, - car_emissions#show, ""

:

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

edit, ""

+3

Try:

resources :reservations do 
  resource :car_emissions
end

-, Singular Resources:

http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default

:

: 2.5

, ID. , , /profile . map/profile ( /profile/: id) show:

get 'profile', to: 'users#show'

#, :

get 'profile', to: :show

:

resource :geocoder

, Geocoders.

+1

shallow: true ,

resources :reservations, shallow: true do 
  resources :car_emissions
end

shallow: true index, create new :car_emissions :reservations. update .

, :

GET  /reservations/:reservation_id/car_emissions(.:format)   caremissions#index
POST     /reservations/:reservation_id/car_emissions(.:format)   caremissions#create
GET  /reservations/:reservation_id/car_emission/new(.:format) caremissions#new

GET  /reservations/:id/edit(.:format)    reservations#edit
PATCH    /reservations/:id(.:format)     reservations#update
PUT  /reservations/:id(.:format)     reservations#update
DELETE   /reservations/:id(.:format)     reservations#destroy
GET  /reservations/:id(.:format)     reservations#show
+1

http://localhost:3000/reservations/1/car_emission

given the emissions of cars for leisure resources, and therefore using it for simple editing, like the one you used above, may run into other resources.

You can optionally create a separate Singular resource and direct it to the desired route.

+1
source

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


All Articles