无法路由到子资源 - 嵌套路由

时间:2017-07-05 13:10:48

标签: ruby-on-rails ruby routes nested

我几天来一直在撞击这个......

我的routes.rb文件如下所示:

resources :vehicles do
 member do
   resources :services  
 end
end

我的service.rb文件显示:

class Service < ActiveRecord::Base
  belongs_to :vehicle
end

我的vehicle.rb文件显示:

class Vehicle < ActiveRecord::Base
  has_many :services, :dependent => :destroy
end

这是services_controller.rb

class ServicesController < ApplicationController

  def index
    @vehicle = Vehicle.find(params[:id])
    @services = @vehicle.services.order('created_at DESC')
  end

  def show
    @vehicle = Vehicle.find(params[:id])
    @service = Vehicle.services.find(params[:service_id])
  end

  def new
    @vehicle = Vehicle.find(params[:id])
    @service = @vehicle.services.new
  end 

  def create
    @vehicle = Vehicle.find(params[:id])
    @service = @vehicle.services.build(service_params)
    if @service.save
      redirect_to @vehicle
    else
      render :new
    end
  end


  private
    def service_params
       params.require(:service).permit(:service_option, :odometer, 
   :current_service, :price, :comments, :next_service)
  end

end

这是服务#index

<h1>Services</h1>


<% @services.each do |s| %>
  <%= link_to "Details", service_path(s) %>
  <%= s.created_at %>
  <%= s.service_option %>
  <%= s.odometer %><br>
<% end %>

点击“详细信息”链接或手动输入网址

  

http://localhost:3000/vehicles/2/services/7

系统地给出了相同的路由错误:

  

ServicesController#show中的ActiveRecord :: RecordNotFound     找不到'id'= 7

的车辆
Extracted source (around line #10):

def show
   @vehicle = Vehicle.find(params[:id])
   @service = Vehicle.services.find(params[:service_id])
end

它将SERVICE ID传递给车辆对象/变量,我不知道为什么!

万分感谢!

1 个答案:

答案 0 :(得分:1)

services#show方法中,您使用错误参数获取vehicleserviceVehicle.services也是错误的,应该是@vehicle.services

def show
  @vehicle = Vehicle.find(params[:vehicle_id])
  @service = @vehicle.services.find(params[:id])
end

<强> 更新

你应该删除路线中的member,否则它会产生像

这样的路线
service GET  /vehicles/:id/services/:id(.:format)  services#show

无关

resources :vehicles do
  resources :services  
end

现在你将拥有像

这样的路线
service GET  /vehicles/:vehicle_id/services/:id(.:format)  services#show

是相关的,您可以使用params[:vehicle_id]获取车辆并使用params[:id]

服务

不要忘记更改路线助手。例如,service_path将成为vehicle_service_path

<%= link_to "Details", vehicle_service_path(@vehicle,s) %>