【发布时间】:2017-06-30 18:18:44
【问题描述】:
这是我的第一个 Rails 项目,我是所有代码的新手,而不仅仅是 Ruby,所以如果我没有简明地解释我的问题,请原谅我。
我有一个模型 Car,它属于另一个模型 User。我希望我的 Cars 索引页面显示数据库中的所有汽车,所以我制作了一个自定义路线“/cars/”,而不是 Rails 生成的 :user_id/cars/:id 路线。
汽车信息正在输出到我的索引页面,但我不知道如何生成返回汽车展示页面的链接。
我确信这很简单,但我整天都在阅读 Rails 指南和其他问题,但还没有解决它。
这里是块:
<% @cars.each do |car| %>
<li>
<div class="well row <%= cycle('', 'white-bg') %>">
<div class="col-sm-4 text-center">
<!-- thumbnail for car here -->
</div>
<div class="pull-left">
<%= link_to car.id, user_car_path(@user, car) do %>
<h3><%= car.year %> <%=car.make %> <%= car.model %></h3>
<% end %>
</div>
<div>
<h3 class="pull-right"><%= car.price %></h3>
</div>
</div>
</li>
<% end %>
路线:
get 'cars' => 'cars#index', as: :cars
resources :users do
resource :profile
resources :cars, except: :index
end
结束
控制器:
def new
@user = User.find( params[:user_id] )
@car = @user.cars.build
end
# POST request to /users/:user_id/cars
def create
@user = User.find( params[:user_id] )
@car = @user.cars.build( car_params )
if @car.save
redirect_to user_path( params[:user_id] )
end
end
# GET request to /users/:user_id/cars/:id
def show
@user = User.find( params[:user_id] )
@car = @user.cars.find( params[:id] )
end
# GET request to /cars/
def index
@cars = Car.all
end
错误是: 没有路线匹配 {:action=>"show", :controller=>"cars", :id=>"1", :user_id=>nil} 缺少必需的键:[:user_id]
我猜我在控制器中遗漏了一些东西,但我在那里尝试的所有东西都会产生其他错误。
谢谢!
cars_path GET /cars(.:format) cars#index
POST /cars(.:format) cars#create
new_car_path GET /cars/new(.:format) cars#new
edit_car_path GET /cars/:id/edit(.:format) cars#edit
car_path GET /cars/:id(.:format) cars#show
PATCH /cars/:id(.:format) cars#update
PUT /cars/:id(.:format) cars#update
删除 /cars/:id(.:format) cars#destroy
new_user_profile_path GET /users/:user_id/profile/new(.:format) 个人资料#new
edit_user_profile_path GET /users/:user_id/profile/edit(.:format)
个人资料#edit
user_profile_path GET /users/:user_id/profile(.:format)
个人资料#show
PATCH /users/:user_id/profile(.:format)profiles#update
PUT /users/:user_id/profile(.:format) 配置文件#update
删除 /users/:user_id/profile(.:format) 个人资料#destroy
POST /users/:user_id/profile(.:format) 个人资料#create
user_cars_path GET /users/:user_id/cars(.:format) cars#index
POST /users/:user_id/cars(.:format) cars#create
new_user_car_path GET /users/:user_id/cars/new(.:format) cars#new
GET /cars/:id/edit(.:format) cars#edit
GET /cars/:id(.:format) 汽车#show
PATCH /cars/:id(.:format) cars#update
PUT /cars/:id(.:format) cars#update
删除 /cars/:id(.:format) cars#destroy
【问题讨论】:
-
能否请您发布运行
rake routes的结果? -
抱歉,我错过了您之前的回复。我已将当前路线添加到 OP,尽管它们与我发布问题时不同,因为我遵循了 Max 在下面的建议。还没有完全启动和运行,所以如果你能提供帮助,我将不胜感激!
标签: ruby-on-rails