2013-02-25 50 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