2012-07-10 94 views
0

我第一次創建了一個非常基本的Rails應用程序,有2個資源部門(部門)和成員。我相信我已經正確地使用嵌套資源,但由於某種原因在運行rails server之後,父資源的id不會正確生成/傳遞。 Root是depts#索引,從這裏我可以使用新和編輯視圖中呈現的_form.haml進行新建和編輯。但是,當我做/ depts/3時,出現「無法找到ID = 3的部門」的錯誤。點擊索引編輯可以在URL中爲我/ depts/63 /編輯 - 我不確定這個id = 63來自哪裏。嘗試通過在URL中輸入/ dept/63來進入「顯示」操作不起作用。我首先創建了Depts,然後讓它處理所有操作和視圖,自從我添加成員資源後出現了問題。Rails應用程序生成錯誤:父控制器中的ID

的routes.rb

 resources :depts do 
    resources :members 
end 

depts_controller.rb

def index 
     @depts = Dept.all 

     respond_to do |format| 
      format.html 
      format.json { render :json => @depts } 
     end 
     end 

     def show 
     @dept = Dept.find(params[:dept_id]) 

     respond_to do |format| 
      format.html 
      format.json { render :json => @dept } 
     end 
     end 

     def new 
     @dept = Dept.new(params[:dept]) 

     respond_to do |format| 
      format.html 
      format.json { render :json => @dept } 
     end 
     end 

     def create 
     @dept = Dept.new(params[:dept]) 

     respond_to do |format| 
      if @dept.save 
      format.html { redirect_to :action => 'index' } 
      format.json { render :json => @dept } 
      else 
      format.html { render :action => 'new' } 
      format.json { render :json => @dept } 
      end 
     end 
     end 

     def edit 
     @dept = Dept.find(params[:id]) 
     end 

     def update 
     @dept = Dept.find(params[:id]) 

     respond_to do |format| 
      if @dept.update_attributes(params[:dept]) 
      format.html { redirect_to :action => 'index'}#, :id => @dept } 
      format.json { render :json => @dept } 

      else 
      format.html { redirect_to :action => 'edit' } 
      format.json { render :json => @dept } 
      end 
     end 
     end 

    def destroy 
     @dept = Dept.find(params[:id]) 
     @dept.destroy 

     respond_to do |format| 
      format.html { redirect_to :action => 'index' } 
      format.json { render :json => @dept } 
     end 
     end 
    end 

show.haml

%p= @dept.name 

    %p= link_to "back", {:action => 'index'} 

index.haml

%h1 DEPARTMENTS 

    %ol 
     - @depts.each do |d| 
     %li= link_to d.name 
     %p= link_to 'edit department', edit_dept_path(d) 
     %p= link_to 'get rid of department!', d, :method => :delete, :id => d.id 

     %br 
    %p= link_to "ADD A NEW DEPARTMENT", new_dept_path 

回答

0

在顯示方式改變:

@dept = Dept.find(params[:dept_id]) 

到:

@dept = Dept.find(params[:id]) 

和新方法的變化:

@dept = Dept.new(params[:dept]) 

只是:

@dept = Dept.new 
相關問題