正如标题所示我试图列出一个特定用户的所有车辆,每辆车都有两个选项显示并更新
如图所示,我的问题是当我想要显示或编辑所选择的汽车时,它会路由(查看图像的左下角)它会占用所有汽车的所有ID,例如用户/“id “/ cars /”id1“/”id2“代替取特定车辆的id:users /”id“/ cars /”id1“/ 这是te index.html.erb文件:
<div class="container">
<h1>Listing Cars</h1>
<table class="table table-condensed">
<tr>
<th>Brand</th>
<th>Color</th>
<th>Model</th>
<th>Year</th>
<th></th>
<th></th>
</tr>
<% @car.each do |car| %>
<tr>
<td><%= car.brand %></td>
<td><%= car.color %></td>
<td><%= car.model %></td>
<td><%= car.year %></td>
<td><%= link_to 'Show', user_car_path(@user,@car) %></td>
<td><%= link_to 'Edit', edit_user_car_path(@user, @car) %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New car', new_user_car_path, :class => "btn btn-primary" %>
</div>
以及是否需要汽车控制器:
class CarsController < ApplicationController
def new
@user = User.find(params[:user_id])
@car = @user.cars.build
end
def create
@user = User.find(params[:user_id])
@car = @user.cars.build(params[:car])
if @car.save
redirect_to user_car_path(@user, @car), :flash => { :notice => " car created!" }
else
redirect_to new_user_car_path ,:flash => { :notice => " sorry try again :(" }
end
end
def show
@user = User.find(params[:user_id])
@car = @user.cars.find(params[:id])
#redirect_to user_car_path(@user, @car)
end
def index
@user = User.find(params[:user_id])
@car = @user.cars.all
end
def edit
@user = User.find(params[:user_id])
@car = @user.cars.find(params[:id])
#redirect_to user_car_path(@user, @car)
end
def update
@user = User.find(params[:user_id])
@car = @user.cars.find(params[:id])
if @car.update_attributes(params[:car])
redirect_to user_cars_path, :flash => { :notice => " Car Updated!" }
else
render 'edit'
end
end
end
答案 0 :(得分:2)
在Ruby枚举器中,块变量是枚举器的每个成员,一个接一个。因此,如果您的示例代码中@cars
为["Toyota", "Mazda", "Honda"]
,则car
将首先为"Toyota"
,然后为"Mazda"
,然后为"Honda"
。< / p>
当你应该使用block变量时,这是一个很长的说法你正在使用实例变量。 ;)将您的代码更正为:
<% @car.each do |car| %>
<tr>
<td><%= car.brand %></td>
<td><%= car.color %></td>
<td><%= car.model %></td>
<td><%= car.year %></td>
<td><%= link_to 'Show', user_car_path(@user, car) %></td>
<td><%= link_to 'Edit', edit_user_car_path(@user, car) %></td>
</tr>
<% end %>
您的路线应该是car
,而不是@car
。