2017-05-27 194 views
0

我有一個名爲「userinfo」的用戶配置文件控制器,它是相應的視圖。 userinfo索引是根路徑。在主頁(這是用戶信息索引),我有一個鏈接,可以將您帶到用戶個人資料頁面。它給我這個錯誤,當我去到主頁:enter image description here爲什麼在嘗試訪問rails中的實例時遇到recordnotfound錯誤?

我的路線是:enter image description here 我userinfos_controller:

class UserinfosController < ApplicationController 
    before_action :find_userinfo, only: [:show, :edit, :update, :destroy] 
    before_action :authenticate_user! 

    def index 
     @userinfors = Userinfo.find(params[:id]) 
    end 

    def show 
     @myvideo = Video.last 
    end 

    def new 
     @userinformation = current_user.userinfos.build 
    end 

    def create 
     @userinformation = current_user.userinfos.build(userinfo_params) 
     if @userinformation.save 
      redirect_to root_path 
     else 
      render 'new' 
     end 
    end 

    def edit 
    end 

    def update 
    end 

    def destroy 
     @userinformation.destroy 
     redirect_to userinfo_path 
    end 

    private 
     def userinfo_params 
      params.require(:userinfo).permit(:name, :email, :college, :gpa, :major) 
     end 

     def find_userinfo 
      @userinformation = Userinfo.find(params[:id]) 
     end 
end 

,我的看法是:

<%= link_to 'profile', userinfors_path(@userinfors) %> 

我的路線。 rb文件:

Rails.application.routes.draw do 
    devise_for :users 
    resources :userinfos do 
    resources :videos 
    end 
    resources :pages 
    get '/application/decide' => 'application#decide' 
    root 'userinfos#index' 
    get '/userinfos/:id', to: 'userinfos#show', as: 'userinfors' 
end 

感謝您的任何幫助!

回答

1

好的,有多個錯誤,你沒有遵循rails的慣例,index不是你所使用的。 Index用於列出所有用戶,show用於特定的用戶id通過params

你的索引路徑是,你可以看到,/userinfos這是正確的,它不會有任何id但你正在努力尋找userparams[:id]這是nil,因此錯誤。

讓我們試試這個:

def index 
    @userinfors = Userinfo.all #pagination is recommended 
end 

在索引視圖,

<% @userinfors.each do |userinfor| %> 
    <%= link_to "#{userinfor.name}'s profile", userinfo_path(userinfor) %> 
<% end %> 

應該現在的工作。

請仔細閱讀routingaction controller,才能認識和了解魔術背後軌路由MVC架構 ..

+0

謝謝!我試圖使用快捷方式,因爲我不想在不同控制器之間創建關聯。但是,你的方式是有效的。 – Dinukaperera

+0

你可以根據你的需要絕對地操作導軌,但是需要理解標準的方法..不管怎樣,很高興它有助於.. :) –

相關問題