-
Notifications
You must be signed in to change notification settings - Fork 241
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
parent doesn't work when building associationg without saving to database #64
Comments
There is one more thing about it, that can help create the tests and solve the problem: c1.root?
=> true
c1.child?
=> false c1.root? should return false and c1.child? should return true... I've double checked my example, and by using "inverse_of" on both sides of the relations definition, solved it. |
I can write the tests if you point me which spec you would like it to be in... here is a patch to solve the problem I reported:
|
Sweet, thanks, but it seems like that doesn't quite make it work. Am I missing something? Check out ce25cf1 — and the travis build: https://travis-ci.org/mceachen/closure_tree/builds/8485398 |
In running this in the debugger, I think inverse is a red-herring. I don't believe Rails supports bi-directional references when the parent doesn't have an ID. This, for example, works without your patch—but note that I'm doing a context "Parent/child inverse relationships" do
it "should associate both sides of the parent and child relationships" do
parent = Label.create!(:name => 'parent')
child = parent.children.build(:name => 'child')
parent.should be_root
parent.should_not be_leaf
child.should_not be_root
child.should be_leaf
end
end |
Oh, sorry, I missed one thing... you can't check for "parent_id", the id will only be filled after the database persistence, but "parent" will refer to the correct object. You will probably want to check if it's "persisted" (.persisted?) to prevent a "useless" database query. The idea is close to the code below: def root?
if persisted?
_ct_parent_id.nil?
else
parent.nil?
end
end |
Nice, I'll change it to that. On Wednesday, June 26, 2013, Gabriel Mazetto wrote:
|
Released with v4.2.4. Thanks for your help! |
I have a really specific model validation that must ensure parent is not defined to enable some validations.
The problem is that if I create both the parent and the children without saving to the database (via build), it fails. Here is a code snippet:
here is how to make it fail:
I've searched for the problem and found this patch submmited to rails 2.3.6 (it's old but still there): https://rails.lighthouseapp.com/projects/8994/tickets/2815-nested-models-build-should-directly-assign-the-parent
The solution is to use "inverse_of" while defining the associations. In theory it will fix this error.
The text was updated successfully, but these errors were encountered: