2013-02-25 49 views
0

我有一個用戶模型,有很多朋友。我試圖給朋友分頁,但我收到了一個沒有這樣的列錯誤。解決方案似乎在這裏回答Rails, SQLException: no such column,但我只是不明白,答案不夠。沒有這樣的列:user_id錯誤rails分頁的朋友

有人可以幫我解釋什麼是錯的,以及如何解決它?

在我home.html.erb

<div class="span8"> 
    <ol class="friends"> 
      <%= render @friends %> 
     </ol> 
     <%= will_paginate @friends %> 
</div> 
在我_friends局部

<li> 
    <span class="friendname"><%= friend.name %></span> 
    <span class="friendid"><%= friend.friendid %></span> 
</li> 

控制器

def home 
    @friends = current_user.friends.paginate(page: params[:page]) 
end 

CURRENT_USER以sessions_helper定義爲:

def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
end 

朋友模型

class Friend < ActiveRecord::Base 
    attr_accessible :friendid, :name, :uid 
    belongs_to :user 
    validates :uid, presence: true 
    validates :friendid, presence: true, uniqueness: true 
end 

用戶模型

class User < ActiveRecord::Base 
    attr_accessible :name, :provider, :uid 
    has_many :friends, dependent: :destroy 
    validates :uid, presence:true, uniqueness:true 
    . 
    . 
    . 
end 

回答

0

如果有人遇到這個問題,朋友模型正在尋找user_id作爲關聯這兩個模型的關鍵。您可以通過鍵入self.primary_key = 'name of column'來設置任意型號的主鍵,然後將該列設置爲在foreign_key=>'name of column from second model'的第二個型號中查找。

0

你應該添加一個名爲user_id列到你的餐桌。要做到這一點,您必須創建遷移並運行它。

+0

爲什麼連列user_id都需要? – 2013-02-25 20:44:51

+0

「belongs_to:user」 因此,您必須在朋友中擁有user_id列。 http://guides.rubyonrails.org/association_basics.html – AKovtunov 2013-02-25 20:47:01

+0

嗯謝謝你的鏈接。基於此,在我的用戶模型中將':foreign_key =>「uid」, :association_foreign_key =>「uid」'修復了我的錯誤?我假設這將用戶模型(外鍵)的uid連接到我朋友模型(關聯外鍵)的uid。是對的嗎? – 2013-02-25 20:51:15