2017-05-27 112 views
-1

我有一個名爲「userinfo」的用戶配置文件控制器,它是相應的視圖。 userinfo索引是根路徑。在主頁(這是用戶信息索引),我有一個鏈接,可以將您帶到用戶個人資料頁面。它給我這個錯誤,當我在圖像上單擊視圖頁上:enter image description here 我的路線是: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.where(:userinfo_id => @userinformation_user_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 image_tag("student.png", class: 'right'), userinfo_path(@userinfors) %> 

我想,也許我必須在控制器頂部的'before_action:find_userinfo'中包含':index'。如果我這樣做,網頁甚至不加載,這讓我這個錯誤:enter image description here

回答

1

試試下面的代碼:

控制器

def index 
    @userinfors = Userinfo.where(:userinfo_id => @userinformation_user_id) #pass id instead of object @userinformation_user_id 
end 

視圖

<% @userinfors.each do |u| %> 
    <%= link_to image_tag("student.png", class: 'right'), userinfo_path(u) %> 
<% end %> 
+0

嗨,你有沒有改變控制器中的任何東西?另外,我應該在控制器的「before_action」中添加':index'嗎? – Dinukaperera

+0

@Dinukaperera你必須通過id而不是instace變量userinformation_user_id – puneet18

1

你的問題是你正在嘗試執行基於不是ActiveRecord(數據庫)屬性的查詢。

您的根源去UserinfosController哪些期望@userinformation_user_id,但我不能告訴你的代碼,從哪裏來。

+0

嘿,哥們,哪一部分你感到困惑?感謝您的幫助! – Dinukaperera

1

您需要定義爲了你的路線,這將是期待一個特定的PARAM,也許用戶id,然後你可以將您的視圖中添加值,在link_to幫手:

你可以修改你的routes.rb期待的id爲PARAM:

get '/user_infors/:id', to: 'userinfos#index', as: 'userinfo_path' 

然後在你的控制器,使用find在數據庫中「發現」這樣的ID的用戶。如果你想使用where那麼這會給你一個userinfosid作爲參數傳遞的關係。 如果你想的話,那麼使用Userinfo.where('userinfo_id = ?', params[:id])

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

,然後在視圖中,可以訪問@userinfors

<% @userinfors.each do |user| %> 
    <%= link_to image_tag 'student.png', class: 'right', userinfo_path(user) %> 
<% end %> 

我想你可以定義index讓所有的userinforsshow方法來獲取特定的一個,就像你正在做的那樣。

+0

非常感謝,你能幫我理解你的最後一行嗎? 「一種獲得特定的展示方法」?我怎麼做?另外,我是否必須在控制器的before_action中添加「:index」? – Dinukaperera

+0

而在路線中,爲什麼它是'/ user_infors /:id'?「user_infors」來自哪裏? – Dinukaperera

+0

我的意思是,如果您想要查找某條記錄並「顯示」它,則只有一條記錄,可以用show方法執行,另一方面,如果要顯示可以使用的所有記錄索引方法。 '/ user_infors'是你的索引路由,'/ user_infors /:id'就是獲得一個特定的記錄。 –

相關問題