0

as the title says I'm trying to list all cars of one specific user, also each car has two options show and update enter image description here

as you see in the picture, my problem is when I want to show or edit the selected car, it routes (look the bottom left of the image) it takes all the ids of all the cars for example users/"id"/cars/"id1"/"id2" instead to take the id of the specific car: users/"id"/cars/"id1"/ here is te index.html.erb file:

<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>

and whether you need the car controller:

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
4

1 回答 1

2

在 Ruby 枚举器中,块变量是枚举器的每个成员,一个接一个。因此,如果在您的示例代码中@carsis ["Toyota", "Mazda", "Honda"], thencar将是 first "Toyota", then "Mazda", then "Honda"

当您应该使用块变量时,这是说您使用实例变量的方式很长。;) 更正您的代码,使其如下所示:

  <% @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,在您的路线中。

于 2012-07-26T15:13:54.277 回答