"parent" does not work if the primary key is not :id
AlvaroMaceda opened this issue · 3 comments
When upgrading from 3.2.1 to 4.2.1, I've found that the gem can't work with non-standard primary key names:
class NonStandard < ApplicationRecord
self.primary_key = "whatever"
end
NonStandard.first.parent
*** ActiveRecord::StatementInvalid Exception: Mysql2::Error: Unknown column 'non_standard.id' in 'where clause'
In this case it's caused because the new version is doing a find_by id:
instead of a find
:
def parent
if has_parent?
unscoped_where do |scope|
scope.find_by id: parent_id
end
end
end
Old code:
def parent
unscoped_find(parent_id) if ancestors?
end
def unscoped_find id
unscoped_where do |scope|
scope.find id
end
end
So the find_by
avoided throwing an exception that the find
had.
I could have sworn that looking up by id
would swap in the primary key when there a non standard primary_key was used.
Do you want to put an a pr that uses class.primary_key => parent_id
?
Oooooooof. I can't use this any more. I want to store multiple parallel ancestries in a single table under separate FKs. Huge block now.
yea. that is part of the original design.
I have ideas to remove this constraint but it introduces a breaking change (and still needs lot more work) so that has stalled me for a few years.
Not sure your time frame but maybe closure trees will meet your need.