Reputation: 6029
Is there a better way to return the "siblings" of the children in a one-to-many relationship in Rails? Assume standard associations have been set up.
For instance, now I would do something like:
child.parent.children
Or, to exclude the current record,
child.parent.children - [child]
This feels a bit dirty (Demeter violation?)... is there a more acceptable best practice?
Upvotes: 3
Views: 1470
Reputation: 5740
As far as I know, there is no out-of-the-box way to do this.
Not going to be radical about it, but this is more acceptable, in the sense that it won't transform your output:
child.parent.children.where.not(id:child.id)
One other way to make it available to your objects, in Model (child.rb) definition:
def siblings
parent.children.where.not(id:self.id)
end
and then you will have:
child.siblings
exactly as above
Upvotes: 7