在Active Record中返回兄弟姐妹(child.parent.children)

Eri*_*man 3 activerecord ruby-on-rails

有没有更好的方法在Rails中以一对多的关系返回孩子们的"兄弟姐妹"?假设已经建立了标准关联.

例如,现在我会做类似的事情:

child.parent.children

或者,要排除当前记录,

child.parent.children - [child]

这感觉有点脏(Demeter违规?)......有更可接受的最佳做法吗?

Rub*_*cer 6

据我所知,没有开箱即用的方法来做到这一点.

不会激进,但这是更可接受的,因为它不会改变你的输出:

child.parent.children.where.not(id:child.id)
Run Code Online (Sandbox Code Playgroud)

在Model(child.rb)定义中,另一种使对象可用的方法:

def siblings
    parent.children.where.not(id:self.id)
end
Run Code Online (Sandbox Code Playgroud)

然后你将拥有:

child.siblings
Run Code Online (Sandbox Code Playgroud)

完全如上