在Rails中,我可以过滤一对多关系而不更新数据库吗?

我正在使用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') }

有没有办法做到这一点?

bcy63997863 回答:在Rails中,我可以过滤一对多关系而不更新数据库吗?

Parent模型中添加实例方法

def filtered_children
  children.where.not("name like ?",'%foo%')
end

在需要时调用filtered_children,重置现有的关联实例变量没有任何意义。相同的查询被缓存,因此无论您调用一次还是多次都没有关系。但是,您始终可以memoize的方法输出,以确保第二次以后不再对该方法进行评估,

def filtered_children
  @filtered_children ||= children.where.not("name like ?",'%foo%')
end

希望有帮助!

,

正在进行数据库更新,因为已将过滤后的记录分配回parent.children。相反,可以使用另一个变量。

filtered_children = parent.children.reject { |child| child.name.include?('foo') }

本文链接:https://www.f2er.com/3107863.html

大家都在问