0

我在我的 Rails 应用程序中创建了一个 FriendRequest.rb 模型,其中包含下表列。

 create_table "friend_requests", force: true do |t|
    t.integer  "requesting_user_id"
    t.integer  "requested_friend_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

使用如下所示定义的关系,我将此代码添加到/views/users/show.html.erb页面中,显示已为每个用户发出的好友请求。但是,我收到此错误

PG::UndefinedColumn: ERROR:  column friend_requests.user_id does not exist

因为,我显然没有创建 user_id 列。有没有一种方法可以通过向关系添加更多信息来使这段代码工作?还是我应该放弃我的工作并以不同的方式做?

 <% for user in @user.friend_requests %>
  <li><%= h user.name %></li>
  <%= link_to "Add Friend", friend_requests_path(:friend_id => user), :method => :post %>
  <% end %>

用户.rb

 has_many :friend_requests

好友请求.rb

   belongs_to :user
4

3 回答 3

2

只需将您的has_many关联更改为:

has_many :friend_requests, foreign_key: 'requesting_user_id'

By default, Rails will look for [model_name]_id in the other table, this is why it is looking for user_id, but by adding the foerign_key: option, you can override this default behaviour and tell Rails what is the name of the foreign_key you want to use.

于 2013-10-07T18:20:35.047 回答
2

You can use this configuration:

class User < ActiveRecord::Base
  has_many :friend_requests
  has_many :requesters, through: friend_requests
end

class FriendRequest < ActiveRecord::Base
  belongs_to :requester, foreign_key: 'requesting_user_id'
  belongs_to :requested, foreign_key: 'requested_friend_id'
  validates :requester_id, presence: true
  validates :requested_id, presence: true
end
于 2013-10-07T18:20:45.517 回答
0

看一眼:

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

特别寻找选项:primary_key:foreign_key

于 2013-10-07T18:13:38.523 回答