有没有更好的方法来返回 Rails 中一对多关系中 child 的“ sibling ”?假设标准协会已经成立。
例如,现在我会做这样的事情:
child.parent.children
或者,排除当前记录,
child.parent.children - [child]
这感觉有点脏(Demeter violation?)...是否有更可接受的最佳实践?
最佳答案
据我所知,没有现成的方法可以做到这一点。
不会太激进,但这是更容易接受的,因为它不会改变您的输出:
child.parent.children.where.not(id:child.id)
在模型 (child.rb) 定义中使其对您的对象可用的另一种方法:
def siblings
parent.children.where.not(id:self.id)
end
然后你将拥有:
child.siblings
和上面一样
关于ruby-on-rails - 在 Active Record 中返回 sibling (child.parent.children),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26347184/