nobrainer icon indicating copy to clipboard operation
nobrainer copied to clipboard

Can't use compound index with association ID

Open CodeMonkeySteve opened this issue 9 years ago • 2 comments

I'm trying to create a compound index that includes a belongs-to association. Here's a short example:

class Source
  include NoBrainer::Document
  has_many :items
end
class Item
  include NoBrainer::Document
  belongs_to :source
  field :gid, required: true, unique: { scope: :source }
  index [:source, :gid]
end
NoBrainer.sync_indexes

source = Source.create!
Item.create!(source: source, gid: 'foo')
Item.where(source: source, gid: 'foo').first

If I specify the index as [:source, :gid], the where call gives a warning that no index is used.

If I specify the index as [:source_id, :gid], it tries to use the index, but fails with:

Array keys can only contain numbers, strings, bools,  pseudotypes, or arrays (got null of type NULL). (RethinkDB::ReqlNonExistenceError)
Backtrace:
r.table("items").get_all([nil, "foo"], {"index" => :source_id_gid}).count

CodeMonkeySteve avatar Jul 18 '16 22:07 CodeMonkeySteve

This is indeed a bug that needs to be fixed in the scope declaration of the unique constraint.

Meanwhile, you can declare the scope to be source_id instead of source:

  field :gid, required: true, unique: { scope: :source_id }

nviennot avatar Jul 18 '16 23:07 nviennot

Setting the scope and the index to use source_id works, thanks.

CodeMonkeySteve avatar Jul 18 '16 23:07 CodeMonkeySteve