使用Postgres在Rails中设置外键

时间:2016-10-08 05:00:04

标签: ruby-on-rails ruby

我试图跟踪用户喜欢喜欢它们的用户的相互喜欢。为了检查是否是相互的,我在创建之后调用一个方法。如果说这个人比他们认为是相互的那样。

问题是,我遇到了一些奇怪的错误,我认为这些错误与外键的设置方式有关。我在Rails中设置了很多关联,但是每当我尝试访问它时,都会出现PG::InFailedSqlTransaction: ERROR: current transaction is aborted, commands ignored until end of transaction block : RELEASE SAVEPOINT active_record_1错误。

用户:

class User < ApplicationRecord
  has_many :likes
end

像:

class Like < ApplicationRecord
  belongs_to :likee, class_name: 'User', foreign_key: 'likee_id'
  belongs_to :liker, class_name: 'User', foreign_key: 'liker_id'
  belongs_to :connection, optional: true

  after_save :mutual_like?

  private

  def mutual_like?

    if liker.likes.where(likee: liker)
      # fails
    end
  end
end

我已经尝试将钩子更改为保存等,但这也不起作用。

另外,我甚至无法拨打Like.first否则我会收到同样的错误。

我已经尝试打印出liker.likes.where(likee: liker),我得到了PG::UndefinedColumn: ERROR: column likes.user_id does not exist,我认为这是问题所在。

但是,我可以像这样访问liker:self.likee但我无法在没有返回self.likee.likes的情况下调用#<Like::ActiveRecord_Associations_CollectionProxy:0x3fd91ca5ca78>

架构:

  create_table "likes", force: :cascade do |t|
    t.integer  "liker_id",      null: false
    t.integer  "likee_id",      null: false
    t.integer  "connection_id"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
    t.index ["likee_id"], name: "index_likes_on_likee_id", using: :btree
    t.index ["liker_id"], name: "index_likes_on_liker_id", using: :btree
  end





create_table "users", force: :cascade do |t|
    t.string   "email"
    t.string   "username"
    t.string   "password_digest"
    t.boolean  "admin",                default: false
    t.index ["email"], name: "index_users_on_email", using: :btree
    t.index ["username"], name: "index_users_on_username", using: :btree
  end

试验:

RSpec.describe Like, type: :model do
  let(:liker) { Fabricate(:user) }
  let(:likee) { Fabricate(:user) }
  let(:like) { Fabricate(:like, liker: liker, likee: likee) }
  let(:pending_like) { Fabricate.build(:like, liker: liker, likee: likee)}

  context 'relations' do
    it { should belong_to :likee }
    it { should belong_to :liker }

    describe 'liking another user' do

      it '#liker references first user' do
        expect(like.likee).to eq likee
      end

      it '#likee references second user' do
        expect(like.liker).to eq liker
      end

    end
  end
  ...

RSpec.describe User, type: :model do
  context 'relations' do
    it { should have_many :likes }
  end
 ...

这是因为我正在尝试查找正在保存的记录吗?

1 个答案:

答案 0 :(得分:2)

liker.likes.where(likee: liker)仅返回关系。您必须像liker.likes.where(likee: liker).exists?

一样执行查询 has_many :likes模型中的

User要求您的表user_id中的列likes。根据给出的代码,我认为你必须将其改为

class User < ApplicationRecord
  has_many :other_likes, foreign_key: :liker_id 
  has_many :likes, foreign_key: :likee_id 
end
在我看来,

belongs_to :connection是个坏名字。 ActiveRecord::Base有一个具有相同名称的类方法。 也许有一天你会遇到这种关联名称的问题。