2012-07-10 77 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