2012-07-26 71 views
0

正如標題所說我想列出一個特定用戶的所有汽車,還每節車廂有兩個選項顯示和更新enter image description here列表中的所有用戶對象

,你在圖片中看到,我的問題是,當我想顯示或編輯選定的汽車,它的路線(看圖像的左下角),它採取所有汽車的所有ID,例如用戶/「ID」/汽車/「ID1」/「ID2」,而不是採取具體車ID:用戶/ 「ID」/汽車/ 「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 

回答

2

在Ruby枚舉器中,block變量是枚舉器的每個成員,一個接一個。因此,如果在您的示例代碼中,@cars["Toyota", "Mazda", "Honda"],那麼car將首先是"Toyota",然後是"Mazda",然後是"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,在你的路由。

+0

非常感謝我修復了它 – Asantoya17 2012-07-26 15:16:40

相關問題