在 ActiveRecord 关系上设置 attr_accessor 值

Set attr_accessor value on ActiveRecord Relation

我有一个 ActiveRecord 关系,我想从中设置一个不持久的属性。不幸的是,它不起作用。

我认为查看问题的最佳方式就是查看代码:

class Post < ActiveRecord::Base
  attr_accessor :search
end

在我的控制器中我有:

results.where(id: search_posts).each do |result_out_of_search|
  result_out_of_search.search = true
end
results.where(id: search_posts).first.search #returns nil

提前致谢

试试这个

results = results.where(id: search_posts)

results.each do |result_out_of_search|
  result_out_of_search.search = true
end

results.first.search

您需要先将记录加载到内存中。由于 results.where(id: search_posts) 导致数据库查询,这不是您想要的。您需要加载到内存中,然后从内存中检索它。

您未将 search 属性视为 true 的原因是您在第二次调用时再次获取帖子。正如您所说,该属性不会持久化,因此您需要确保您使用的是相同的帖子集合。如果您在控制台中 运行 您的代码,或者查看服务器的日志,您会看到获取帖子的查询 运行 两次。

为确保您使用的是同一个集合,您需要明确地跟踪它而不是再次执行 results.where(...)

posts = results.where(id: search_posts)
posts.each do |result_out_of_search|
  result_out_of_search.search = true
end
posts.first.search # Should be true

如果您只是装饰搜索结果,您也可以从 gem 中获得一些价值,例如 draper,它很好地概括了这个想法。