ruby-on-rails - 在 Active Record 中返回 sibling (child.parent.children)

标签 ruby-on-rails activerecord

有没有更好的方法来返回 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/

相关文章:

ruby-on-rails - Rails 组/用户成员协会最佳实践

activerecord - ActiveRecord通过表的位置和顺序

mysql - 如何在 where 子句中使用 SOUNDS LIKE

ruby-on-rails - 创建到外部 URL 的 Rails 路由

ruby-on-rails - 使用 JBuilder 内联数组元素

ruby-on-rails - Rails 4.2.0 中简单整数赋值的 RangeError 应该被验证捕获

ruby-on-rails - 未知 key : :expression. 有效 key 为 : :unique, :order, :name, :where, :length, :internal, :using, :algorithm, :type

ruby-on-rails - Rails 4 批量更新模型数组

ruby-on-rails - 如何轻松地将生产 postgresql 数据库克隆到暂存区

ruby-on-rails - 如何使 Rails Heroku 应用程序内容可在 google 中搜索?