我几天来一直在撞击这个......
我的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 %>
点击“详细信息”链接或手动输入网址
系统地给出了相同的路由错误:
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传递给车辆对象/变量,我不知道为什么!
万分感谢!
答案 0 :(得分:1)
在services#show
方法中,您使用错误参数获取vehicle
和service
。 Vehicle.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) %>