Ruby on Rails嵌套路由与has_one关联

8

I have two models:

Reservation:

class Reservation < ActiveRecord::Base
  has_one :car_emission
end

车辆排放:

class CarEmission < ActiveRecord::Base
  belongs_to :reservation
end

以及以下路由:

resources :reservations do 
  resources :car_emissions
end

现在,当我想创建新的car_emission时,我必须访问像这样的URL:
http://localhost:3000/reservations/1/car_emissions/new

当我想要编辑时,我必须访问:
http://localhost:3000/reservations/1/car_emissions/1/edit

有没有办法更改路由,使得我的car_emission编辑链接看起来像这样:
http://localhost:3000/reservations/1/car_emission
4个回答

12

你想要做几件事情:

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

单数资源

@sreekanthGS所建议的,你最好首先创建一个单数资源。这与resources方法的工作方式相同,只是把你的路由视为单个记录;没有index路由等:

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

编辑

这将为你的car_emission创建一组RESTful路由,但当你点击“裸链接”时,它仍将带您到car_emissions#show操作。

最好采用以下方式:

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

点击“无样式”链接将带您到编辑操作页面。


4

尝试:

resources :reservations do 
  resource :car_emissions
end

有一种资源叫做奇异资源(Singular Resources):
引用:http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default 2.5 奇异资源: 有时候你会有这样一个资源,客户端总是查找它而不引用 ID。例如:你希望 /profile 总是显示当前登录用户的个人资料。在这种情况下,你可以使用奇异资源将 /profile(而不是 /profile/:id)映射到 show 操作。
get 'profile', to: 'users#show'

将字符串传递给get方法时,需要使用controller#action格式,而将符号传递给它将直接映射到一个操作:
get 'profile', to: :show

这个有用的路径:
resource :geocoder

在您的应用程序中创建六个不同的路由,都映射到Geocoders控制器。


1

shallow: true 可能是你想要的

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

shallow: true会将:car_emissionsindexcreatenew操作嵌套在: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

Link of this type

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

为了展示汽车排放的RESTful资源,需要使用它来进行简单的编辑,就像您上面使用的那个可能会与RESTful资源冲突。
您可以选择创建一个单独的Singular资源,并将其定向到所需的路由。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接