我正在使用Rails 5,并且希望能够过滤一对多关系,以便仅将子项的子集发送给客户端。数据模型是非常标准的,看起来像这样:
class Parent < ApplicationRecord
has_many :children,class_name: 'Child'
end
class Child < ApplicationRecord
belongs_to :parent
end
当客户打电话时,我只想返回Child
实例中的 some 个Parent
。
这也很复杂,因为关于Child
对象应该返回的逻辑非常复杂,所以我在Ruby中而不是在数据库中进行操作。
每当我执行以下操作时,Rails都会尝试更新数据库以删除关联。我不希望数据库被更新。我只想在将结果发送到客户端之前对其进行过滤。
parent.children = parent.children.reject { |child| child.name.include?('foo') }
有没有办法做到这一点?