简体   繁体   English

在ActiveRecord关系上设置attr_accessor值

[英]Set attr_accessor value on ActiveRecord Relation

I have an ActiveRecord Relation from which I would like to set an attribute not persisted. 我有一个ActiveRecord关系,我想从中设置一个不持久的属性。 Unfortunately, it is not working. 不幸的是,它不起作用。

I think the best way of seeing the problem is just seeing the code: 我认为解决问题的最好方法就是看代码:

class Post < ActiveRecord::Base
  attr_accessor :search
end

In my controller I have: 在我的控制器中,我有:

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

Thanks in advance 提前致谢

Try this 尝试这个

results = results.where(id: search_posts)

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

results.first.search

You need to load the records to the memory first. 您需要先将记录加载到内存中。 As results.where(id: search_posts) results in a db query, it is not what u want. 由于results.where(id: search_posts)导致数据库查询,这不是您想要的。 You need to load to the memory, and then retrieve it from the memory. 您需要加载到内存,然后从内存中检索它。

The reason you're not seeing your search attributes as true is because you are fetching the posts again wit the second call. 您没有将search属性视为真实的原因是因为您要通过第二次调用再次获取帖子。 As you say, the attribute is not persisted so you need to ensure that you are working with the same collection of posts. 如您所说,该属性不是持久性的,因此您需要确保使用相同的帖子集。 If you run your code in the console, or look at the logs from the server, you'll see the query to fetch posts being run twice. 如果您在控制台中运行代码,或者查看服务器中的日志,则会看到查询以获取两次运行的帖子。

To ensure you're using the same collection you need to keep track of it explicitly rather than doing results.where(...) again: 为了确保您使用的是相同的集合,您需要明确地跟踪它,而不是再次执行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

If you are just decorating search results you may also get some value from a gem like draper which encapsulates that idea quite nicely. 如果您只是装饰搜索结果,则还可以从诸如draper之类的宝石中获得一些价值,该宝石可以很好地封装该想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM